diff --git a/App/Screens/About/About.tsx b/App/Screens/About/About.tsx
index 6984df95..83412eb9 100644
--- a/App/Screens/About/About.tsx
+++ b/App/Screens/About/About.tsx
@@ -30,7 +30,6 @@ import { NavigationInjectedProps } from 'react-navigation';
import { Box } from './Box';
import { BackButton } from '../../components';
-import { Dev } from './Dev';
import { i18n } from '../../localization';
import * as theme from '../../util/theme';
@@ -186,7 +185,6 @@ export function About (props: AboutProps) {
{/* Add languages https://github.com/amaurymartiny/shoot-i-smoke/issues/73 */}
-
);
}
diff --git a/App/Screens/About/Dev/Dev.tsx b/App/Screens/About/Dev/Dev.tsx
deleted file mode 100644
index 01b529b1..00000000
--- a/App/Screens/About/Dev/Dev.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import * as BackgroundFetch from 'expo-background-fetch';
-import * as ExpoLocation from 'expo-location';
-import { pipe } from 'fp-ts/lib/pipeable';
-import * as T from 'fp-ts/lib/Task';
-import * as TE from 'fp-ts/lib/TaskEither';
-import React, { useEffect, useState } from 'react';
-import { AsyncStorage, Text, View } from 'react-native';
-
-import { Button } from '../../../components';
-import {
- AqiHistoryDbItem,
- clearTable,
- getData,
- populateRandom
-} from '../../../managers/AqiHistoryDb';
-import {
- AQI_HISTORY_LAST_FETCH_ATTEMPT,
- AQI_HISTORY_LAST_FETCH_RESULT
-} from '../../../managers/AqiHistoryTask';
-import { getLastKnownGps, GPS_TASK } from '../../../managers/GpsTask';
-import { logFpError } from '../../../util/fp';
-import * as theme from '../../../util/theme';
-
-export function Dev () {
- const [allData, setAllData] = useState([]);
- const [
- aqiHistoryTask,
- setAqiHistoryTask
- ] = useState(null);
- const [bgLocation, setBgLocation] = useState(false);
- const [startedBgLocation, setStartedBgLocation] = useState(false);
- const [asyncStorageGps, setAsyncStorageGps] = useState();
- const [lastBgFetchAttempt, setLastBgFetchAttempt] = useState();
- const [lastBgFetchResult, setLastBgFetchResult] = useState();
-
- useEffect(() => {
- // Data in SQL db
- const oneWeekAgo = new Date();
- oneWeekAgo.setHours(oneWeekAgo.getHours() - 24 * 7);
- pipe(
- getData(oneWeekAgo),
- TE.fold(
- err => {
- console.log(` - getData - Error ${err.message}`);
-
- return T.of(undefined);
- },
- data => {
- setAllData(data);
- return T.of(undefined);
- }
- )
- )().catch(logFpError);
-
- // GPS_TASK status
- ExpoLocation.isBackgroundLocationAvailableAsync().then(setBgLocation);
- ExpoLocation.hasStartedLocationUpdatesAsync(GPS_TASK).then(
- setStartedBgLocation
- );
- pipe(
- getLastKnownGps(),
- TE.fold(
- err => {
- console.log(` - getLastKnownGps - Error ${err.message}`);
-
- return T.of(undefined);
- },
- data => {
- setAsyncStorageGps(data);
- return T.of(undefined);
- }
- )
- )().catch(logFpError);
-
- // AQI_HISTORY_TASK status
- BackgroundFetch.getStatusAsync().then(setAqiHistoryTask);
- AsyncStorage.getItem(AQI_HISTORY_LAST_FETCH_ATTEMPT).then(
- setLastBgFetchAttempt
- );
- AsyncStorage.getItem(AQI_HISTORY_LAST_FETCH_RESULT).then(
- setLastBgFetchResult
- );
- }, []);
-
- return (
-
-
- BackgroundFetch status:{' '}
- {aqiHistoryTask && BackgroundFetch.Status[aqiHistoryTask]}
-
-
- isBackgroundLocationAvailableAsync: {bgLocation.toString()}
-
-
- hasStartedLocationUpdatesAsync: {startedBgLocation.toString()}
-
-
- Last known GPS: {JSON.stringify(asyncStorageGps)}
-
- Last BackgroundFetch: {lastBgFetchAttempt}
-
- Last BackgroundFetch Result: {lastBgFetchResult}
-
-
- All DB:{' '}
- {JSON.stringify(allData.map(({ creationTime }) => creationTime))}
-
-
-
-
- );
-}
diff --git a/App/Screens/About/Dev/index.ts b/App/Screens/About/Dev/index.ts
deleted file mode 100644
index 76637a08..00000000
--- a/App/Screens/About/Dev/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-export * from './Dev';
diff --git a/App/Screens/Details/Header/Header.tsx b/App/Screens/Details/Header/Header.tsx
index 62f37905..2a335834 100644
--- a/App/Screens/Details/Header/Header.tsx
+++ b/App/Screens/Details/Header/Header.tsx
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Sh**t! I Smoke. If not, see .
-import { distanceInWords } from 'date-fns';
+import { formatDistanceToNow } from 'date-fns';
import React, { useContext } from 'react';
import {
GestureResponderEvent,
@@ -63,7 +63,7 @@ export function Header (props: HeaderProps) {
{lastUpdated &&
renderInfo(
i18n.t('details_header_latest_update_label'),
- `${distanceInWords(lastUpdated, new Date())} ${i18n.t(
+ `${formatDistanceToNow(lastUpdated)} ${i18n.t(
'details_header_latest_update_ago'
)}`
)}
diff --git a/App/Screens/Home/Footer/Footer.tsx b/App/Screens/Home/Footer/Footer.tsx
index 3b4fb76c..b74ea778 100644
--- a/App/Screens/Home/Footer/Footer.tsx
+++ b/App/Screens/Home/Footer/Footer.tsx
@@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Sh**t! I Smoke. If not, see .
-import * as O from 'fp-ts/lib/Option';
-import { pipe } from 'fp-ts/lib/pipeable';
import React, { useContext } from 'react';
import { Share, StyleSheet, Text, View } from 'react-native';
import { NavigationInjectedProps } from 'react-navigation';
@@ -23,19 +21,17 @@ import { NavigationInjectedProps } from 'react-navigation';
import { aboutSections } from '../../About';
import { Button } from '../../../components';
import { i18n } from '../../../localization';
-import { AqiHistory } from '../../../managers';
import { Frequency } from '../SelectFrequency';
import { ApiContext, CurrentLocationContext } from '../../../stores';
import { isStationTooFar } from '../../../util/station';
import * as theme from '../../../util/theme';
interface FooterProps extends NavigationInjectedProps {
- aqiHistory: O.Option;
frequency: Frequency;
}
export function Footer (props: FooterProps) {
- const { aqiHistory, frequency } = props;
+ const { frequency } = props;
const { api } = useContext(ApiContext)!;
const { currentLocation } = useContext(CurrentLocationContext);
@@ -45,12 +41,6 @@ export function Footer (props: FooterProps) {
props.navigation.navigate('About');
}
- function goToAboutAqiHistory () {
- props.navigation.navigate('About', {
- scrollInto: aboutSections.about_how_results
- });
- }
-
function goToAboutWhySoFar () {
props.navigation.navigate('About', {
scrollInto: aboutSections.about_why_is_the_station_so_far_title
@@ -61,13 +51,6 @@ export function Footer (props: FooterProps) {
props.navigation.navigate('Details');
}
- function goToPastStations () {
- props.navigation.navigate('PastStations', {
- aqiHistory,
- frequency
- });
- }
-
function handleShare () {
return Share.share({
title: i18n.t('home_share_title'),
@@ -78,87 +61,34 @@ export function Footer (props: FooterProps) {
}
const renderBigButton = () => {
- switch (frequency) {
- case 'daily': {
- return isTooFar ? (
-
- ) : (
-
- );
- }
- case 'weekly':
- case 'monthly': {
- return pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.filter(({ isCorrect }) => isCorrect),
- O.map(() => (
-
- )),
- O.getOrElse(() => (
-
- ))
- );
- }
- }
+ return isTooFar ? (
+
+ ) : (
+
+ );
};
const renderSmallButtons = () => {
- switch (frequency) {
- case 'daily': {
- return (
-
- {isTooFar ? (
-
- ) : (
-
- )}
-
-
- );
- }
- case 'weekly':
- case 'monthly': {
- return pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.filter(({ isCorrect }) => isCorrect),
- O.map(() => (
-
-
-
-
- )),
- O.getOrElse(() => null)
- );
- }
- }
+ return (
+
+ {isTooFar ? (
+
+ ) : (
+
+ )}
+
+
+ );
};
return (
diff --git a/App/Screens/Home/Home.tsx b/App/Screens/Home/Home.tsx
index 3c3686d2..aaf7e364 100644
--- a/App/Screens/Home/Home.tsx
+++ b/App/Screens/Home/Home.tsx
@@ -14,11 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Sh**t! I Smoke. If not, see .
-import { pipe } from 'fp-ts/lib/pipeable';
-import * as O from 'fp-ts/lib/Option';
-import * as T from 'fp-ts/lib/Task';
-import * as TE from 'fp-ts/lib/TaskEither';
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useContext, useState } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { NavigationInjectedProps } from 'react-navigation';
@@ -26,14 +22,11 @@ import { Cigarettes } from '../../components';
import { Footer } from './Footer';
import { Header } from './Header';
import { i18n } from '../../localization';
-import { AqiHistory, getAqiHistory } from '../../managers';
import { Frequency, SelectFrequency } from './SelectFrequency';
import { SmokeVideo } from './SmokeVideo';
import { ApiContext, CurrentLocationContext } from '../../stores';
import swearWords from './swearWords';
-import { logFpError } from '../../util/fp';
import * as theme from '../../util/theme';
-import { Wait } from './Wait';
interface HomeProps extends NavigationInjectedProps {}
@@ -48,27 +41,6 @@ export function Home (props: HomeProps) {
const { api } = useContext(ApiContext)!;
const { isGps } = useContext(CurrentLocationContext)!;
const [frequency, setFrenquency] = useState('daily');
- const [aqiHistory, setAqiHistory] = useState>(O.none);
-
- useEffect(() => {
- pipe(
- getAqiHistory(),
- TE.fold(
- err => {
- console.log(` - getAqiHistory - ${err.message}`);
-
- return T.of(undefined);
- },
- history => {
- console.log(` - getAqiHistory - Got data from DB`);
-
- setAqiHistory(O.some(history));
-
- return T.of(undefined);
- }
- )
- )().catch(logFpError);
- }, []);
function getCigaretteCount () {
switch (frequency) {
@@ -76,45 +48,16 @@ export function Home (props: HomeProps) {
return api!.shootISmoke.cigarettes;
}
case 'weekly':
+ return api!.shootISmoke.cigarettes * 7;
case 'monthly': {
- return pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.map(({ sum }) => sum),
- O.getOrElse(() => 0)
- );
+ return api!.shootISmoke.cigarettes * 30;
}
}
}
const cigaretteCount = getCigaretteCount();
function renderCigarettes () {
- switch (frequency) {
- case 'daily': {
- return (
-
- );
- }
- case 'weekly':
- case 'monthly': {
- return pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.map(({ isCorrect }) => isCorrect),
- O.map(isCorrect =>
- isCorrect ? (
-
- ) : (
-
- )
- ),
- O.getOrElse(() => null)
- );
- }
- }
+ return ;
}
const renderCigarettesText = () => {
@@ -123,9 +66,10 @@ export function Home (props: HomeProps) {
const text = i18n.t('home_smoked_cigarette_title', {
swearWord: getSwearWord(cigaretteCount),
- presentPast: isGps
- ? i18n.t('home_common_you_smoke')
- : i18n.t('home_common_you_d_smoke'),
+ presentPast:
+ isGps && frequency === 'daily'
+ ? i18n.t('home_common_you_smoke')
+ : i18n.t('home_common_you_d_smoke'),
singularPlural:
cigarettes === 1
? i18n.t('home_common_cigarette').toLowerCase()
@@ -147,30 +91,6 @@ export function Home (props: HomeProps) {
);
};
- function renderText () {
- switch (frequency) {
- case 'daily': {
- return renderCigarettesText();
- }
- case 'weekly':
- case 'monthly': {
- return pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.chain(({ daysToResults }) => daysToResults),
- O.fold(renderCigarettesText, days => (
-
-
- {i18n.t('home_wait_more_days', { days: days + 1 })}
- {' '}
- {i18n.t('home_wait_until_results')}
-
- ))
- );
- }
- }
- }
-
return (
@@ -184,26 +104,16 @@ export function Home (props: HomeProps) {
>
{renderCigarettes()}
- {renderText()}
- {isGps ? (
- {
- setFrenquency(freq);
- }}
- style={styles.selectFrequency}
- />
- ) : (
-
- {i18n.t('home_smoked_there')}.
-
- )}
+ {renderCigarettesText()}
+ {
+ setFrenquency(freq);
+ }}
+ style={styles.selectFrequency}
+ />
-
+
);
diff --git a/App/Screens/PastStations/PastStations.tsx b/App/Screens/PastStations/PastStations.tsx
deleted file mode 100644
index 09ec9078..00000000
--- a/App/Screens/PastStations/PastStations.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import { format } from 'date-fns';
-import { uniq } from 'fp-ts/lib/Array';
-import { contramap, eqString } from 'fp-ts/lib/Eq';
-import * as O from 'fp-ts/lib/Option';
-import { pipe } from 'fp-ts/lib/pipeable';
-import React from 'react';
-import { FlatList, StyleSheet, Text, View } from 'react-native';
-import { NavigationInjectedProps } from 'react-navigation';
-
-import { BackButton, ListItem, ListSeparator } from '../../components';
-import { Frequency } from '../Home/SelectFrequency';
-import { i18n } from '../../localization';
-import { AqiHistory, AqiHistoryDbItem } from '../../managers/AqiHistoryDb';
-import * as theme from '../../util/theme';
-
-interface Params {
- aqiHistory: O.Option;
- frequency: Frequency;
-}
-
-interface PastStationsProps extends NavigationInjectedProps {}
-
-const UNKNOWN_STATION = i18n.t('').toUpperCase();
-
-// Determine when two `AqiHistoryDbItem` items are equal in the list, so that we
-// only show them once
-const eqStation = contramap(
- (item: AqiHistoryDbItem) => item.station || UNKNOWN_STATION
-)(eqString);
-
-export function PastStations (props: PastStationsProps) {
- const { navigation } = props;
- const aqiHistory = navigation.getParam('aqiHistory');
- const frequency = navigation.getParam('frequency');
-
- if (frequency === 'daily') {
- navigation.pop();
- return;
- }
-
- return (
-
- navigation.pop()} style={theme.withPadding} />
-
-
- {pipe(
- aqiHistory,
- O.map(history => history[frequency]),
- O.fold(
- () => i18n.t('past_stations_loading').toUpperCase(),
- summary =>
- i18n
- .t('past_stations_date_from_to', {
- startDate: format(summary.firstResult, 'DD/MM/YYYY'),
- endDate: format(summary.lastResult, 'DD/MM/YYYY')
- })
- .toUpperCase()
- )
- )}
-
-
- {i18n
- .t(
- frequency === 'weekly'
- ? 'past_stations_monitored_weekly'
- : 'past_stations_monitored_monthly'
- )
- .toUpperCase()}
-
-
-
- history[frequency].data),
- O.map(uniq(eqStation)),
- O.getOrElse(() => [])
- )}
- ItemSeparatorComponent={renderSeparator}
- keyExtractor={({ station }) => station || UNKNOWN_STATION}
- renderItem={renderItem}
- style={styles.list}
- />
-
- );
-}
-
-function renderItem ({ item }: { item: AqiHistoryDbItem }) {
- return (
- x).join(', ') ||
- i18n.t('past_stations_unknown_city')
- }
- icon="pin"
- title={item.station || UNKNOWN_STATION}
- />
- );
-}
-
-function renderSeparator () {
- return ;
-}
-
-const styles = StyleSheet.create({
- container: {
- flexGrow: 1,
- marginTop: theme.spacing.normal
- },
- date: {
- ...theme.title,
- color: theme.primaryColor,
- marginTop: theme.spacing.normal
- },
- description: {
- ...theme.title
- },
- list: {
- flex: 1
- }
-});
diff --git a/App/Screens/PastStations/index.ts b/App/Screens/PastStations/index.ts
deleted file mode 100644
index 2be115d4..00000000
--- a/App/Screens/PastStations/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-export * from './PastStations';
diff --git a/App/Screens/Screens.tsx b/App/Screens/Screens.tsx
index c4337522..f457bf16 100644
--- a/App/Screens/Screens.tsx
+++ b/App/Screens/Screens.tsx
@@ -27,7 +27,6 @@ import { Details } from './Details';
import { ErrorScreen } from './ErrorScreen';
import { Home } from './Home';
import { Loading } from './Loading';
-import { PastStations } from './PastStations';
import { Search } from './Search';
import { ApiContext, ErrorContext } from '../stores';
import { Api } from '../stores/fetchApi';
@@ -61,9 +60,6 @@ const RootStack = createAppContainer(
Home: {
screen: Home
},
- PastStations: {
- screen: PastStations
- },
Search: {
screen: Search
}
diff --git a/App/managers/AqiHistoryDb.ts b/App/managers/AqiHistoryDb.ts
deleted file mode 100644
index 45b442e1..00000000
--- a/App/managers/AqiHistoryDb.ts
+++ /dev/null
@@ -1,437 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import {
- addDays,
- differenceInCalendarDays,
- differenceInSeconds
-} from 'date-fns';
-import { SQLite } from 'expo-sqlite';
-import { array, flatten } from 'fp-ts/lib/Array';
-import * as C from 'fp-ts/lib/Console';
-import * as O from 'fp-ts/lib/Option';
-import { pipe } from 'fp-ts/lib/pipeable';
-import * as T from 'fp-ts/lib/Task';
-import * as TE from 'fp-ts/lib/TaskEither';
-
-import { LatLng } from '../stores/fetchGpsPosition';
-import { pm25ToCigarettes } from '../stores/fetchApi/dataSources/pm25ToCigarettes';
-import { sideEffect, toError } from '../util/fp';
-import { sqlToJsDate } from './util/sqlToJsDate';
-import { sumInDays } from './util/staircaseAverage';
-import { ONE_WEEK_AGO, ONE_MONTH_AGO, NOW } from '../util/time';
-
-// FIXME correct types
-type Database = any;
-type ResultSet = any;
-type Transaction = any;
-
-interface AqiHistoryDbItemInput extends LatLng {
- rawPm25: number;
- station?: string;
- city?: string;
- country?: string;
-}
-
-export interface AqiHistoryDbItem extends AqiHistoryDbItemInput {
- creationTime: string;
- id: number;
-}
-
-export const SAVE_DATA_INTERVAL = 3 * 3600; // 3 hours in s
-const AQI_HISTORY_DB = 'AQI_HISTORY_DB';
-const AQI_HISTORY_TABLE = 'AqiHistory';
-
-/**
- * Open database and create (if not exists) the AqiHistory table.
- */
-function initDb () {
- return pipe(
- TE.rightTask(T.of(SQLite.openDatabase(AQI_HISTORY_DB) as Database)),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- tx.executeSql(
- `
- CREATE TABLE IF NOT EXISTS ${AQI_HISTORY_TABLE} (
- id INTEGER PRIMARY KEY,
- latitude REAL NOT NULL,
- longitude REAL NOT NULL,
- rawPm25 REAL NOT NULL,
- station TEXT,
- city TEXT,
- country TEXT,
- creationTime DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `,
- [],
- () => resolve(db),
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
-
-/**
- * Fetch the db
- */
-function getDb () {
- // TODO Only do initDb once (although that operation is idempotent)
- return initDb();
-}
-
-/**
- * Check if we need to save a new entry (every `SAVE_DATA_INTERVAL`)
- */
-function isSaveNeeded () {
- return pipe(
- getDb(),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- tx.executeSql(
- `
- SELECT * FROM ${AQI_HISTORY_TABLE}
- ORDER BY creationTime DESC
- LIMIT 1
- `,
- [],
- (_transaction: Transaction, resultSet: ResultSet) => {
- try {
- if (resultSet.rows.length === 0) {
- return resolve(true);
- }
-
- // Get the time difference (in ms) between now and last saved
- // item in the db
- const timeDiff = differenceInSeconds(
- NOW,
- sqlToJsDate(resultSet.rows.item(0).creationTime)
- );
-
- if (timeDiff <= SAVE_DATA_INTERVAL) {
- console.log(
- ` - last save happened at ${
- resultSet.rows.item(0).creationTime
- }`
- );
- resolve(false);
- } else {
- resolve(true);
- }
- } catch (err) {
- // It shouldn't throw, but we're never too sure
- reject(err);
- }
- },
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
-
-/**
- * Insert a new row in the table
- *
- * @param value - The value to insert
- */
-function writeToDb (value: AqiHistoryDbItemInput) {
- return pipe(
- getDb(),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- console.log(
- ` - saveData - Inserting new row in ${AQI_HISTORY_TABLE} with values ${JSON.stringify(
- value
- )}`
- );
-
- tx.executeSql(
- `
- INSERT INTO ${AQI_HISTORY_TABLE}
- (latitude, longitude, rawPm25, station, city, country)
- VALUES (?, ?, ?, ?, ?, ?)
- `,
- [
- value.latitude,
- value.longitude,
- value.rawPm25,
- value.station,
- value.city,
- value.country
- ],
- () => resolve(),
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
-
-/**
- * Add a new row in the table, if needed
- *
- * @param value - The entry to add.
- */
-export function saveData (value: AqiHistoryDbItemInput) {
- return pipe(
- isSaveNeeded(),
- TE.chain(isNeeded =>
- TE.rightIO(
- sideEffect(
- C.log(` - saveData - isSaveNeeded=${isNeeded}`),
- isNeeded
- )
- )
- ),
- TE.chain(isNeeded =>
- isNeeded ? writeToDb(value) : TE.right(undefined as void)
- )
- );
-}
-
-/**
- * Get the PM25 data since `date`.
- *
- * @param date - The date to start calculating the PM25.
- */
-export function getData (date: Date) {
- return pipe(
- getDb(),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- tx.executeSql(
- `
- SELECT * FROM ${AQI_HISTORY_TABLE}
- WHERE creationTime > datetime(?)
- ORDER BY creationTime DESC
- `,
- [date.toISOString()],
- (_transaction: Transaction, resultSet: ResultSet) => {
- console.log(
- ` - getData - ${
- resultSet.rows.length
- } results since ${date.toISOString()}`
- );
- resolve(resultSet.rows._array);
- },
-
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
-
-export interface AqiHistorySummary {
- data: AqiHistoryDbItem[];
- daysToResults: O.Option;
- firstResult: Date;
- isCorrect: boolean;
- lastResult: Date;
- numberOfResults: number;
- sum: number;
-}
-
-export interface AqiHistory {
- monthly: AqiHistorySummary;
- weekly: AqiHistorySummary;
-}
-
-/**
- * From historical data, derive a summary
- */
-function computeSummary (
- pastData: AqiHistoryDbItem[],
- weekOrMonth: keyof AqiHistory
-): AqiHistorySummary {
- const firstResult = sqlToJsDate(pastData[pastData.length - 1].creationTime);
-
- // We add some buffer to compute `daysUntilResults`. The idea is that we want
- // the first result in our db to be really one week or one month ago, +/- 1
- // day.
- const oneWeekOrMonthAgo = addDays(
- weekOrMonth === 'weekly' ? ONE_WEEK_AGO : ONE_MONTH_AGO,
- 1
- );
-
- // const firstResult.getTime() - oneWeekOrMonthAgo.getTime() <= 0
- const daysToResults = pipe(
- differenceInCalendarDays(firstResult, oneWeekOrMonthAgo),
- O.fromPredicate(days => days >= 0)
- );
-
- return {
- data: pastData,
- daysToResults,
- firstResult,
- lastResult: sqlToJsDate(pastData[0].creationTime),
- isCorrect: O.isNone(daysToResults),
- numberOfResults: pastData.length,
- sum: pm25ToCigarettes(
- sumInDays(
- pastData.map(({ creationTime, rawPm25 }) => ({
- time: sqlToJsDate(creationTime),
- value: rawPm25
- }))
- )
- )
- };
-}
-
-/**
- * Get data from past week and past month
- */
-export function getAqiHistory () {
- return pipe(
- array.sequence(TE.taskEither)([
- getData(ONE_WEEK_AGO),
- getData(ONE_MONTH_AGO)
- ]),
- TE.map(
- ([pastWeekData, pastMonthData]) =>
- ({
- monthly: computeSummary(pastMonthData, 'monthly'),
- weekly: computeSummary(pastWeekData, 'weekly')
- } as AqiHistory)
- )
- );
-}
-
-/**
- * Clears the whole db. DANGEROUS.
- */
-export function clearTable () {
- return pipe(
- TE.rightIO(
- C.log(` - clearTable - Dropping table ${AQI_HISTORY_TABLE}`)
- ),
- TE.chain(getDb),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- tx.executeSql(
- `DROP TABLE ${AQI_HISTORY_TABLE};`,
- [],
- () => resolve(),
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
-
-export function populateRandom () {
- const randomValues = flatten(
- [...Array(30)].map((_, i) => [
- 0,
- 0,
- Math.floor(Math.random() * 20 + 1),
- `some station ${Math.floor(Math.random() * 10 + 1)}`,
- `some city ${Math.floor(Math.random() * 10 + 1)}`,
- `some country ${Math.floor(Math.random() * 10 + 1)}`,
- new Date(new Date().setDate(new Date().getDate() - i - 1)).toISOString()
- ])
- );
-
- return pipe(
- getDb(),
- TE.chain(db =>
- TE.tryCatch(
- () =>
- new Promise((resolve, reject) => {
- db.transaction((tx: Transaction) => {
- tx.executeSql(
- `
- INSERT INTO ${AQI_HISTORY_TABLE}
- (latitude, longitude, rawPm25, station, city, country, creationTime)
- VALUES
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?),
- (?, ?, ?, ?, ?, ?, ?)
- `,
- randomValues,
- () => {
- console.log(
- ' - populateRandom - Successfully populated random data'
- );
- resolve();
- },
- (_transaction: Transaction, error: Error) => reject(error)
- );
- }, reject);
- }) as Promise,
- toError
- )
- )
- );
-}
diff --git a/App/managers/AqiHistoryTask.ts b/App/managers/AqiHistoryTask.ts
deleted file mode 100644
index 6787556f..00000000
--- a/App/managers/AqiHistoryTask.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import { Result } from 'expo-background-fetch';
-import { defineTask } from 'expo-task-manager';
-import { pipe } from 'fp-ts/lib/pipeable';
-import * as T from 'fp-ts/lib/Task';
-import * as TE from 'fp-ts/lib/TaskEither';
-import { AsyncStorage } from 'react-native';
-import Sentry from 'sentry-expo';
-
-import { getLastKnownGps } from './GpsTask';
-import { fetchApi, saveApi } from '../stores/fetchApi';
-import { logFpError } from '../util/fp';
-
-export const AQI_HISTORY_TASK = 'AQI_HISTORY_TASK';
-export const AQI_HISTORY_LAST_FETCH_ATTEMPT = 'AQI_HISTORY_LAST_FETCH_ATTEMPT';
-export const AQI_HISTORY_LAST_FETCH_RESULT = 'AQI_HISTORY_LAST_FETCH_RESULT';
-
-/**
- * This task will fetch API data from remote and save to SQLite database
- */
-defineTask(AQI_HISTORY_TASK, () => {
- // For dev purposes
- AsyncStorage.setItem(
- AQI_HISTORY_LAST_FETCH_ATTEMPT,
- new Date().toISOString()
- );
-
- return pipe(
- getLastKnownGps(),
- TE.chain(gps =>
- pipe(
- fetchApi(gps),
- TE.chain(api => saveApi(gps, api))
- )
- ),
- TE.fold(
- err => {
- console.log(` - defineTask - Error ${err.message}`);
- Sentry.captureException(err);
-
- // For dev purposes
- AsyncStorage.setItem(AQI_HISTORY_LAST_FETCH_RESULT, err.message);
-
- return T.of(Result.Failed);
- },
- () => T.of(Result.NewData)
- )
- )().catch(error => {
- logFpError(error);
- return Result.Failed;
- });
-});
diff --git a/App/managers/GpsTask.ts b/App/managers/GpsTask.ts
deleted file mode 100644
index eb990bdb..00000000
--- a/App/managers/GpsTask.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import * as C from 'fp-ts/lib/Console';
-import * as E from 'fp-ts/lib/Either';
-import { pipe } from 'fp-ts/lib/pipeable';
-import * as TE from 'fp-ts/lib/TaskEither';
-import { defineTask } from 'expo-task-manager';
-import { AsyncStorage } from 'react-native';
-
-import { LatLng } from '../stores/fetchGpsPosition';
-import { sideEffect, toError } from '../util/fp';
-
-export const GPS_TASK = 'GPS_TASK';
-const GPS_ASYNC_STORAGE = 'GPS_ASYNC_STORAGE';
-
-interface LastKnownGps extends LatLng {
- creationTime: string;
-}
-
-/**
- * Get last saved value of GPS location in async storage
- * TODO Maybe this should return `TaskEither>`
- */
-export function getLastKnownGps () {
- return pipe(
- TE.tryCatch(() => AsyncStorage.getItem(GPS_ASYNC_STORAGE), toError),
- TE.chain(gpsString =>
- TE.fromEither(
- E.fromNullable(new Error(`AsyncStorage ${GPS_ASYNC_STORAGE} is empty`))(
- gpsString
- )
- )
- ),
- TE.chain(gpsString =>
- TE.rightIO(
- sideEffect(
- C.log(
- ` - defineTask - Got last known location ${gpsString}`
- ),
- gpsString
- )
- )
- ),
- TE.chain(gpsString =>
- TE.fromEither(
- E.tryCatch(() => JSON.parse(gpsString) as LastKnownGps, toError)
- )
- )
- );
-}
-
-/**
- * This task will check user GPS location and save to AsyncStorage
- */
-defineTask(GPS_TASK, async ({ data, error }) => {
- try {
- if (error) {
- console.log(` - defineTask - Error ${error.message}`);
- return;
- }
-
- if (data) {
- const { locations } = data as { locations: { coords: LatLng }[] };
- const { coords } = locations[0];
-
- // Using TE.tryCatch here seems overkill
- AsyncStorage.setItem(
- GPS_ASYNC_STORAGE,
- JSON.stringify({
- creationTime: new Date().toISOString(),
- latitude: coords.latitude,
- longitude: coords.longitude
- })
- )
- .then(() =>
- console.log(' - defineTask - Updated Gps Location')
- )
- .catch(error =>
- console.log(` - defineTask - Error ${error.message}`)
- );
- }
- } catch (err) {
- console.log(` - defineTask - Error ${err.message}`);
- }
-});
diff --git a/App/managers/index.ts b/App/managers/index.ts
deleted file mode 100644
index c82544b8..00000000
--- a/App/managers/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-export * from './AqiHistoryDb';
diff --git a/App/managers/util/sqlToJsDate.ts b/App/managers/util/sqlToJsDate.ts
deleted file mode 100644
index 9d88865f..00000000
--- a/App/managers/util/sqlToJsDate.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-/**
- * Convert a SQL date to a JS Date object
- *
- * @param date - The SQL date to convert.
- */
-export function sqlToJsDate (date: string) {
- return new Date(date.replace(' ', 'T'));
-}
diff --git a/App/managers/util/staircaseAverage.spec.ts b/App/managers/util/staircaseAverage.spec.ts
deleted file mode 100644
index 5bfa03b2..00000000
--- a/App/managers/util/staircaseAverage.spec.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import { subDays } from 'date-fns';
-
-import { sumInDays } from './staircaseAverage';
-
-describe('staircaseAverage', () => {
- it('should compute correct values', () => {
- const data = [
- { time: new Date(), value: 3 },
- { time: subDays(new Date(), 1), value: 2 },
- { time: subDays(new Date(), 2), value: 1 }
- ];
-
- expect(sumInDays(data).toFixed(2)).toBe('3.00'); // 1+2, the value=3 is too short to be taken into the sum
- });
-});
diff --git a/App/managers/util/staircaseAverage.ts b/App/managers/util/staircaseAverage.ts
deleted file mode 100644
index 1760c460..00000000
--- a/App/managers/util/staircaseAverage.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-// Sh**t! I Smoke
-// Copyright (C) 2018-2019 Marcelo S. Coelho, Amaury Martiny
-
-// Sh**t! I Smoke is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Sh**t! I Smoke is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Sh**t! I Smoke. If not, see .
-
-import { compareAsc, differenceInMilliseconds } from 'date-fns';
-
-interface Data {
- time: Date;
- value: number;
-}
-
-/**
- * Calculate the integral of a staircase function (the base step on the `x` axis
- * is 1ms)
- *
- * @param data - The data to calculate the integral on
- */
-function staircaseIntegral (data: Data[]): number {
- if (!data.length) {
- return 0;
- }
-
- const sortedData = data.slice().sort((a, b) => compareAsc(a.time, b.time));
-
- return sortedData.reduce(
- (sum, currentValue, index) =>
- sum +
- differenceInMilliseconds(
- sortedData[index + 1] ? sortedData[index + 1].time : new Date(),
- currentValue.time
- ) *
- currentValue.value,
- 0
- );
-}
-
-/**
- * Calculate the sum of values of a staircase function, wich a base step on the
- * `x` axis as 1day
- *
- * @param data - The data to calculate the sum on
- */
-export function sumInDays (data: Data[]): number {
- return staircaseIntegral(data) / (24 * 3600 * 1000);
-}
diff --git a/App/stores/api.tsx b/App/stores/api.tsx
index b0fac422..12f36b7a 100644
--- a/App/stores/api.tsx
+++ b/App/stores/api.tsx
@@ -20,7 +20,7 @@ import * as TE from 'fp-ts/lib/TaskEither';
import React, { createContext, useContext, useEffect, useState } from 'react';
import { ErrorContext } from './error';
-import { Api, fetchApi, saveApi } from './fetchApi';
+import { Api, fetchApi } from './fetchApi';
import { CurrentLocationContext } from './location';
import { logFpError } from '../util/fp';
import { noop } from '../util/noop';
@@ -37,7 +37,7 @@ interface ApiContextProviderProps {
}
export function ApiContextProvider ({ children }: ApiContextProviderProps) {
- const { currentLocation, isGps, setCurrentLocation } = useContext(
+ const { currentLocation, setCurrentLocation } = useContext(
CurrentLocationContext
);
const { setError } = useContext(ErrorContext);
@@ -53,15 +53,6 @@ export function ApiContextProvider ({ children }: ApiContextProviderProps) {
pipe(
fetchApi(currentLocation),
- TE.chain(newApi =>
- isGps
- ? pipe(
- saveApi(currentLocation, newApi),
- TE.orElse(() => TE.right(undefined as void)), // Silently ignore if saveApi fails
- TE.map(() => newApi)
- )
- : TE.right(newApi)
- ),
TE.fold(
err => {
setError(err.message);
diff --git a/App/stores/fetchApi/fetchApi.ts b/App/stores/fetchApi/fetchApi.ts
index 35537c2d..a8a2bd01 100644
--- a/App/stores/fetchApi/fetchApi.ts
+++ b/App/stores/fetchApi/fetchApi.ts
@@ -24,9 +24,7 @@ import { failure } from 'io-ts/lib/PathReporter';
import { Location } from '../fetchGpsPosition';
import * as dataSources from './dataSources';
-import { saveData } from '../../managers/AqiHistoryDb';
import { retry, sideEffect, toError } from '../../util/fp';
-import { isStationTooFar } from '../../util/station';
const ApiT = t.type({
aqi: t.number,
@@ -74,9 +72,7 @@ export function fetchApi (gps: Location) {
pipe(
TE.rightIO(
C.log(
- ` - fetchApi - Attempt #${status.iterNumber}: ${
- sources[(status.iterNumber - 1) % sources.length].name
- }`
+ ` - fetchApi - Attempt #${status.iterNumber}: ${sources[(status.iterNumber - 1) % sources.length].name}`
)
),
TE.chain(() =>
@@ -108,16 +104,3 @@ export function fetchApi (gps: Location) {
)
);
}
-
-export function saveApi (gps: Location, api: Api) {
- return isStationTooFar(gps, api)
- ? TE.left(new Error('Station too far, not saving'))
- : saveData({
- latitude: gps.latitude,
- longitude: gps.longitude,
- rawPm25: api.shootISmoke.rawPm25,
- station: api.shootISmoke.station,
- city: gps.city,
- country: gps.country
- });
-}
diff --git a/App/stores/fetchGpsPosition/fetchGpsPosition.ts b/App/stores/fetchGpsPosition/fetchGpsPosition.ts
index 4a88c8f6..178bdb6b 100644
--- a/App/stores/fetchGpsPosition/fetchGpsPosition.ts
+++ b/App/stores/fetchGpsPosition/fetchGpsPosition.ts
@@ -14,16 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Sh**t! I Smoke. If not, see .
-import * as BackgroundFetch from 'expo-background-fetch';
import * as ExpoLocation from 'expo-location';
import * as Permissions from 'expo-permissions';
-import { isTaskRegisteredAsync } from 'expo-task-manager';
import * as TE from 'fp-ts/lib/TaskEither';
import { pipe } from 'fp-ts/lib/pipeable';
-import { SAVE_DATA_INTERVAL } from '../../managers/AqiHistoryDb';
-import { AQI_HISTORY_TASK } from '../../managers/AqiHistoryTask';
-import { GPS_TASK } from '../../managers/GpsTask';
import { toError } from '../../util/fp';
export interface LatLng {
@@ -73,25 +68,6 @@ export function fetchGpsPosition () {
throw new Error('Permission to access location was denied');
}
- // Start the task to record periodically on the background the location
- const isGpsRegistered = await isTaskRegisteredAsync(GPS_TASK);
- if (!isGpsRegistered) {
- ExpoLocation.startLocationUpdatesAsync(GPS_TASK);
- }
- // Start the task to record periodically on the background the location
- const isAqiRegistered = await isTaskRegisteredAsync(AQI_HISTORY_TASK);
- if (!isAqiRegistered) {
- await BackgroundFetch.registerTaskAsync(AQI_HISTORY_TASK, {
- minimumInterval: SAVE_DATA_INTERVAL, // in s
- startOnBoot: true,
- stopOnTerminate: false
- });
- // Apparently this is needed
- // https://github.com/expo/expo/issues/3582#issuecomment-480924126
- // https://github.com/expo/expo/issues/3582#issuecomment-520035731
- await BackgroundFetch.setMinimumIntervalAsync(SAVE_DATA_INTERVAL);
- }
-
return ExpoLocation.getCurrentPositionAsync({
timeout: 5000
});
diff --git a/package.json b/package.json
index def2864c..1a0d185e 100644
--- a/package.json
+++ b/package.json
@@ -23,14 +23,12 @@
"date-fns": "^2.2.1",
"expo": "^34.0.4",
"expo-av": "~6.0.0",
- "expo-background-fetch": "~6.0.0",
"expo-constants": "~6.0.0",
"expo-font": "~6.0.1",
"expo-localization": "~6.0.0",
"expo-location": "~6.0.0",
"expo-permissions": "~6.0.0",
"expo-sqlite": "~6.0.0",
- "expo-task-manager": "~6.0.0",
"fp-ts": "^2.0.5",
"haversine": "^1.1.1",
"i18n-js": "^3.3.0",
diff --git a/yarn.lock b/yarn.lock
index c8dbdea8..0942f3d6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3004,13 +3004,6 @@ expo-av@~6.0.0:
lodash "^4.17.11"
nullthrows "^1.1.0"
-expo-background-fetch@~6.0.0:
- version "6.0.0"
- resolved "https://registry.yarnpkg.com/expo-background-fetch/-/expo-background-fetch-6.0.0.tgz#4a1d8ffeea73e5ff8113a8c8c57d689a6ddfb6c6"
- integrity sha512-30JAE+MC/f1Gzfg9Zs40rHas0DCF0aTiF9V/YCRuPo2a08HE1CfEmMeEibuxKiYlAZp8C8Z35/UEcSY1UJHfFg==
- dependencies:
- expo-task-manager "~6.0.0"
-
expo-constants@~6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/expo-constants/-/expo-constants-6.0.0.tgz#ff4598985ba006e24949be3f05be7429e5bedacf"
@@ -3070,11 +3063,6 @@ expo-sqlite@~6.0.0:
"@types/websql" "^0.0.27"
lodash "^4.17.11"
-expo-task-manager@~6.0.0:
- version "6.0.0"
- resolved "https://registry.yarnpkg.com/expo-task-manager/-/expo-task-manager-6.0.0.tgz#acab77771ccdfaa7318df446542263e50aef46e2"
- integrity sha512-7+zwpoSRrt1NnWqetnq51gSpFhecYafIONJyI6WebHqVvPuWNcBwp3+96nhFoKLnuBQdf0CTw3iJbbj2ujvf5A==
-
expo-web-browser@~6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/expo-web-browser/-/expo-web-browser-6.0.0.tgz#63a59d4c02cd7ba47faa6a2eb04decb1a1ab2a32"