Merge pull request #772 from pangeachat/move-server-main

Move server main
pull/1476/head
ggurdin 1 year ago committed by GitHub
commit aa22cb8596
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -56,6 +56,7 @@ class Environment {
return dotenv.env["RC_IOS_KEY"] ?? 'appl_DUPqnxuLjkBLzhBPTWeDjqNENuv'; return dotenv.env["RC_IOS_KEY"] ?? 'appl_DUPqnxuLjkBLzhBPTWeDjqNENuv';
} }
// This is a public key
static String get rcStripeKey { static String get rcStripeKey {
return dotenv.env["RC_STRIPE_KEY"] ?? 'strp_YWZxWUeEfvagiefDNoofinaRCOl'; return dotenv.env["RC_STRIPE_KEY"] ?? 'strp_YWZxWUeEfvagiefDNoofinaRCOl';
} }

@ -327,7 +327,10 @@ class SubscriptionController extends BaseController {
SubscriptionDuration duration, { SubscriptionDuration duration, {
bool isPromo = false, bool isPromo = false,
}) async { }) async {
final Requests req = Requests(baseUrl: PApiUrls.baseAPI); final Requests req = Requests(
choreoApiKey: Environment.choreoApiKey,
accessToken: _pangeaController.userController.accessToken,
);
final String reqUrl = Uri.encodeFull( final String reqUrl = Uri.encodeFull(
"${PApiUrls.paymentLink}?pangea_user_id=$userID&duration=${duration.value}&redeem=$isPromo", "${PApiUrls.paymentLink}?pangea_user_id=$userID&duration=${duration.value}&redeem=$isPromo",
); );

@ -10,7 +10,6 @@ import 'package:jwt_decode/jwt_decode.dart';
import 'package:matrix/matrix.dart' as matrix; import 'package:matrix/matrix.dart' as matrix;
import '../models/user_model.dart'; import '../models/user_model.dart';
import '../repo/user_repo.dart';
/// Controller that manages saving and reading of user/profile information /// Controller that manages saving and reading of user/profile information
class UserController extends BaseController { class UserController extends BaseController {
@ -124,26 +123,6 @@ class UserController extends BaseController {
// wait for account data to load // wait for account data to load
// as long as it's not null, then this we've already migrated the profile // as long as it's not null, then this we've already migrated the profile
await _pangeaController.matrixState.client.waitForAccountData(); await _pangeaController.matrixState.client.waitForAccountData();
if (profile.userSettings.dateOfBirth != null) {
return;
}
// we used to store the user's profile in the pangea server
// we now store it in the matrix account data
final PangeaProfileResponse? resp = await PUserRepo.fetchPangeaUserInfo(
userID: userId!,
matrixAccessToken: _matrixAccessToken!,
);
// if it's null, we don't have a profile in the pangea server
if (resp?.profile == null) {
return;
}
// if we have a profile in the pangea server, we need to migrate it to the matrix account data
final userSetting = UserSettings.fromJson(resp!.profile.toJson());
final newProfile = Profile(userSettings: userSetting);
await newProfile.saveProfileData(waitForDataInSync: true);
} }
/// Reinitializes the user's profile /// Reinitializes the user's profile

@ -9,58 +9,65 @@ import 'package:fluffychat/pangea/config/environment.dart';
/// ///
/// https://api.staging.pangea.chat/api/v1/ /// https://api.staging.pangea.chat/api/v1/
class PApiUrls { class PApiUrls {
static String baseAPI = Environment.baseAPI; static String choreoPrefix = "/choreo";
static String subscriptionPrefix = "/subscription";
static String accountPrefix = "/account";
static String choreoEndpoint =
"${Environment.choreoApi}${PApiUrls.choreoPrefix}";
static String subscriptionEndpoint =
"${Environment.choreoApi}${PApiUrls.subscriptionPrefix}";
static String accountEndpoint =
"${Environment.choreoApi}${PApiUrls.accountPrefix}";
/// ---------------------- Languages -------------------------------------- /// ---------------------- Languages --------------------------------------
static String getLanguages = "/languages"; static String getLanguages = "${PApiUrls.choreoEndpoint}/languages";
/// ---------------------- Users -------------------------------------- /// ---------------------- Users --------------------------------------
static String createUser = "/account/create"; static String paymentLink = "${PApiUrls.subscriptionEndpoint}/payment_link";
static String userDetails = "/account/get_user_access_token?pangea_user_id=";
static String updateUserProfile = "/account/update";
static String paymentLink = "/account/payment_link";
static String subscriptionExpiration = "/account/premium_expires_date";
/// ---------------------- Conversation Partner ------------------------- /// ---------------------- Conversation Partner -------------------------
static String searchUserProfiles = "/account/search"; /// PTODO: Migrate or remove
static String searchUserProfiles = "${PApiUrls.accountEndpoint}/search";
///-------------------------------- choreo -------------------------- ///-------------------------------- choreo --------------------------
static String igc = "${Environment.choreoApi}/grammar"; static String igc = "${PApiUrls.choreoEndpoint}/grammar";
static String languageDetection = static String languageDetection =
"${Environment.choreoApi}/language_detection"; "${PApiUrls.choreoEndpoint}/language_detection";
static String igcLite = "${Environment.choreoApi}/grammar_lite"; static String igcLite = "${PApiUrls.choreoEndpoint}/grammar_lite";
static String spanDetails = "${Environment.choreoApi}/span_details"; static String spanDetails = "${PApiUrls.choreoEndpoint}/span_details";
static String wordNet = "${Environment.choreoApi}/wordnet"; static String wordNet = "${PApiUrls.choreoEndpoint}/wordnet";
static String contextualizedTranslation = static String contextualizedTranslation =
"${Environment.choreoApi}/translation/contextual"; "${PApiUrls.choreoEndpoint}/translation/contextual";
static String simpleTranslation = static String simpleTranslation =
"${Environment.choreoApi}/translation/direct"; "${PApiUrls.choreoEndpoint}/translation/direct";
static String tokenize = "${Environment.choreoApi}/tokenize"; static String tokenize = "${PApiUrls.choreoEndpoint}/tokenize";
static String contextualDefinition = static String contextualDefinition =
"${Environment.choreoApi}/contextual_definition"; "${PApiUrls.choreoEndpoint}/contextual_definition";
static String similarity = "${Environment.choreoApi}/similarity"; static String similarity = "${PApiUrls.choreoEndpoint}/similarity";
static String topicInfo = "${Environment.choreoApi}/vocab_list"; static String topicInfo = "${PApiUrls.choreoEndpoint}/vocab_list";
static String itFeedback = "${Environment.choreoApi}/translation/feedback"; static String itFeedback = "${PApiUrls.choreoEndpoint}/translation/feedback";
static String firstStep = "/it_initialstep"; static String firstStep = "${PApiUrls.choreoEndpoint}/it_initialstep";
static String subseqStep = "/it_step"; static String subseqStep = "${PApiUrls.choreoEndpoint}/it_step";
static String textToSpeech = "${Environment.choreoApi}/text_to_speech"; static String textToSpeech = "${PApiUrls.choreoEndpoint}/text_to_speech";
static String speechToText = "${Environment.choreoApi}/speech_to_text"; static String speechToText = "${PApiUrls.choreoEndpoint}/speech_to_text";
static String messageActivityGeneration = static String messageActivityGeneration =
"${Environment.choreoApi}/practice/message"; "${PApiUrls.choreoEndpoint}/practice/message";
///-------------------------------- revenue cat -------------------------- ///-------------------------------- revenue cat --------------------------
static String rcApiV1 = "https://api.revenuecat.com/v1"; static String rcApiV1 = "https://api.revenuecat.com/v1";
static String rcApiV2 =
"https://api.revenuecat.com/v2/projects/${Environment.rcProjectId}";
static String rcApps = "$rcApiV2/apps"; static String rcAppsChoreo = "${PApiUrls.subscriptionEndpoint}/app_ids";
static String rcProducts = "$rcApiV2/offerings?expand=items.package.product"; static String rcProductsChoreo =
static String rcSubscribers = "$rcApiV1/subscribers"; "${PApiUrls.subscriptionEndpoint}/all_products";
static String rcSubscription = "$rcApiV1/subscribers";
} }

@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:developer'; import 'dart:developer';
import 'package:fluffychat/pangea/utils/error_handler.dart'; import 'package:fluffychat/pangea/utils/error_handler.dart';
import 'package:fluffychat/widgets/matrix.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
@ -44,9 +45,12 @@ class GenerateImageRequest {
class ImageRepo { class ImageRepo {
static Future<GenerateImageeResponse> fetchImage( static Future<GenerateImageeResponse> fetchImage(
GenerateImageRequest request) async { GenerateImageRequest request,
final Requests req = ) async {
Requests(baseUrl: Environment.choreoApi); // Set your API base URL final Requests req = Requests(
choreoApiKey: Environment.choreoApiKey,
accessToken: MatrixState.pangeaController.userController.accessToken,
); // Set your API base URL
final requestBody = request.toJson(); final requestBody = request.toJson();
try { try {
@ -58,7 +62,8 @@ class ImageRepo {
if (res.statusCode == 200) { if (res.statusCode == 200) {
final decodedBody = jsonDecode(utf8.decode(res.bodyBytes)); final decodedBody = jsonDecode(utf8.decode(res.bodyBytes));
return GenerateImageeResponse.fromJson( return GenerateImageeResponse.fromJson(
decodedBody); // Convert response to ImageModel decodedBody,
); // Convert response to ImageModel
} else { } else {
throw Exception('Failed to load image'); throw Exception('Failed to load image');
} }

@ -1,8 +1,9 @@
import 'dart:convert'; import 'dart:convert';
import 'package:fluffychat/pangea/config/environment.dart';
import 'package:fluffychat/widgets/matrix.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:fluffychat/pangea/config/environment.dart';
import '../models/custom_input_translation_model.dart'; import '../models/custom_input_translation_model.dart';
import '../models/it_response_model.dart'; import '../models/it_response_model.dart';
import '../models/system_choice_translation_model.dart'; import '../models/system_choice_translation_model.dart';
@ -14,8 +15,8 @@ class ITRepo {
CustomInputRequestModel initalText, CustomInputRequestModel initalText,
) async { ) async {
final Requests req = Requests( final Requests req = Requests(
baseUrl: Environment.choreoApi,
choreoApiKey: Environment.choreoApiKey, choreoApiKey: Environment.choreoApiKey,
accessToken: MatrixState.pangeaController.userController.accessToken,
); );
final Response res = final Response res =
await req.post(url: PApiUrls.firstStep, body: initalText.toJson()); await req.post(url: PApiUrls.firstStep, body: initalText.toJson());
@ -29,8 +30,8 @@ class ITRepo {
SystemChoiceRequestModel subseqText, SystemChoiceRequestModel subseqText,
) async { ) async {
final Requests req = Requests( final Requests req = Requests(
baseUrl: Environment.choreoApi,
choreoApiKey: Environment.choreoApiKey, choreoApiKey: Environment.choreoApiKey,
accessToken: MatrixState.pangeaController.userController.accessToken,
); );
final Response res = final Response res =

@ -1,18 +1,20 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:developer'; import 'dart:developer';
import 'package:fluffychat/pangea/config/environment.dart';
import 'package:fluffychat/pangea/models/language_model.dart'; import 'package:fluffychat/pangea/models/language_model.dart';
import 'package:fluffychat/pangea/network/urls.dart'; import 'package:fluffychat/pangea/network/urls.dart';
import 'package:fluffychat/pangea/utils/error_handler.dart'; import 'package:fluffychat/pangea/utils/error_handler.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
import '../config/environment.dart';
import '../network/requests.dart'; import '../network/requests.dart';
class LanguageRepo { class LanguageRepo {
static Future<List<LanguageModel>> fetchLanguages() async { static Future<List<LanguageModel>> fetchLanguages() async {
final Requests req = Requests(baseUrl: Environment.choreoApi); final Requests req = Requests(
choreoApiKey: Environment.choreoApiKey,
);
final Response res = await req.get(url: PApiUrls.getLanguages); final Response res = await req.get(url: PApiUrls.getLanguages);
final decodedBody = final decodedBody =

@ -3,28 +3,30 @@ import 'dart:convert';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:fluffychat/pangea/config/environment.dart'; import 'package:fluffychat/pangea/config/environment.dart';
import 'package:fluffychat/pangea/controllers/subscription_controller.dart'; import 'package:fluffychat/pangea/controllers/subscription_controller.dart';
import 'package:fluffychat/pangea/network/requests.dart';
import 'package:fluffychat/pangea/utils/error_handler.dart'; import 'package:fluffychat/pangea/utils/error_handler.dart';
import 'package:fluffychat/pangea/utils/subscription_app_id.dart'; import 'package:fluffychat/pangea/utils/subscription_app_id.dart';
import 'package:fluffychat/widgets/matrix.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../network/urls.dart'; import '../network/urls.dart';
class SubscriptionRepo { class SubscriptionRepo {
static final Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${Environment.rcKey}',
};
static Future<SubscriptionAppIds?> getAppIds() async { static Future<SubscriptionAppIds?> getAppIds() async {
try { try {
final http.Response res = await http.get( final Requests req = Requests(
Uri.parse(PApiUrls.rcApps), choreoApiKey: Environment.choreoApiKey,
headers: SubscriptionRepo.requestHeaders, accessToken: MatrixState.pangeaController.userController.accessToken,
);
final http.Response res = await req.get(
url: PApiUrls.rcAppsChoreo,
);
return SubscriptionAppIds.fromJson(
jsonDecode(res.body),
); );
final json = jsonDecode(res.body);
return SubscriptionAppIds.fromJson(json);
} catch (err) { } catch (err) {
ErrorHandler.logError( ErrorHandler.logError(
m: "Failed to fetch app information for revenuecat API", m: "Failed to fetch app information for revenuecat API",
@ -36,19 +38,19 @@ class SubscriptionRepo {
static Future<List<SubscriptionDetails>?> getAllProducts() async { static Future<List<SubscriptionDetails>?> getAllProducts() async {
try { try {
final http.Response res = await http.get( final Requests req = Requests(
Uri.parse(PApiUrls.rcProducts), choreoApiKey: Environment.choreoApiKey,
headers: SubscriptionRepo.requestHeaders, accessToken: MatrixState.pangeaController.userController.accessToken,
);
final http.Response res = await req.get(
url: PApiUrls.rcProductsChoreo,
); );
final Map<String, dynamic> json = jsonDecode(res.body); final Map<String, dynamic> json = jsonDecode(res.body);
final RCProductsResponseModel resp = final RCProductsResponseModel resp =
RCProductsResponseModel.fromJson(json); RCProductsResponseModel.fromJson(json);
return resp.allProducts; return resp.allProducts;
} catch (err) { } catch (err, s) {
ErrorHandler.logError( ErrorHandler.logError(e: err, s: s);
m: "Failed to fetch entitlement information for revenuecat API",
s: StackTrace.current,
);
return null; return null;
} }
} }
@ -62,7 +64,7 @@ class SubscriptionRepo {
'Accept': 'application/json', 'Accept': 'application/json',
'Authorization': 'Bearer ${Environment.rcStripeKey}', 'Authorization': 'Bearer ${Environment.rcStripeKey}',
}; };
final String url = "${PApiUrls.rcSubscribers}/$userId"; final String url = "${PApiUrls.rcSubscription}/$userId";
final http.Response res = await http.get( final http.Response res = await http.get(
Uri.parse(url), Uri.parse(url),
headers: stripeHeaders, headers: stripeHeaders,
@ -88,26 +90,20 @@ class RCProductsResponseModel {
Map<String, dynamic> json, Map<String, dynamic> json,
) { ) {
final List<dynamic> offerings = json["items"] as List<dynamic>; final List<dynamic> offerings = json["items"] as List<dynamic>;
final offering = offerings.firstWhereOrNull( final res = offerings
Environment.isStaging .map(
? (offering) => !(offering['is_current'] as bool) (offering) => SubscriptionDetails(
: (offering) => offering['is_current'] as bool, price: offering['price'],
); duration: SubscriptionDuration.values.firstWhereOrNull(
final Map<String, dynamic> metadata = offering['metadata']; (duration) => duration.value == offering['duration'],
),
final List<SubscriptionDetails> allProducts = []; id: offering['id'],
for (final packageDetails in offering['packages']['items']) { appId: offering['appId'],
final String packageId = packageDetails['id']; ),
final List<SubscriptionDetails> products = )
RCProductsResponseModel.productsFromPackageDetails( .toList()
packageDetails, .cast<SubscriptionDetails>();
packageId, return RCProductsResponseModel(allProducts: res);
metadata,
);
allProducts.addAll(products);
}
return RCProductsResponseModel(allProducts: allProducts);
} }
static List<SubscriptionDetails> productsFromPackageDetails( static List<SubscriptionDetails> productsFromPackageDetails(

@ -1,66 +1,14 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:developer';
import 'package:fluffychat/pangea/config/environment.dart';
import 'package:fluffychat/pangea/constants/model_keys.dart'; import 'package:fluffychat/pangea/constants/model_keys.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
import '../models/user_model.dart';
import '../models/user_profile_search_model.dart'; import '../models/user_profile_search_model.dart';
import '../network/requests.dart'; import '../network/requests.dart';
import '../network/urls.dart'; import '../network/urls.dart';
class PUserRepo { class PUserRepo {
// static Future<PangeaProfileResponse?> repoCreatePangeaUser({
// required String userID,
// required String dob,
// required fullName,
// required String matrixAccessToken,
// }) async {
// try {
// final Requests req = Requests(
// baseUrl: PApiUrls.baseAPI,
// matrixAccessToken: matrixAccessToken,
// );
// final Map<String, dynamic> body = {
// ModelKey.userFullName: fullName,
// ModelKey.userPangeaUserId: userID,
// ModelKey.userDateOfBirth: dob,
// };
// final resp = await req.post(
// url: PApiUrls.createUser,
// body: body,
// );
// return PangeaProfileResponse.fromJson(jsonDecode(resp.body));
// } catch (err, s) {
// ErrorHandler.logError(e: err, s: s);
// return null;
// }
// }
static Future<PangeaProfileResponse?> fetchPangeaUserInfo({
required String userID,
required String matrixAccessToken,
}) async {
Response res;
try {
final Requests req = Requests(
baseUrl: PApiUrls.baseAPI,
matrixAccessToken: matrixAccessToken,
);
res = await req.get(
url: PApiUrls.userDetails,
objectId: userID,
);
return PangeaProfileResponse.fromJson(jsonDecode(res.body));
} catch (err) {
//status code should be 400 - PTODO - check ffor this.
log("Most likely a first signup and needs to make an account");
return null;
}
}
static Future<UserProfileSearchResponse> searchUserProfiles({ static Future<UserProfileSearchResponse> searchUserProfiles({
// List<String>? interests, // List<String>? interests,
String? targetLanguage, String? targetLanguage,
@ -72,8 +20,8 @@ class PUserRepo {
required int limit, required int limit,
}) async { }) async {
final Requests req = Requests( final Requests req = Requests(
baseUrl: PApiUrls.baseAPI,
accessToken: accessToken, accessToken: accessToken,
choreoApiKey: Environment.choreoApiKey,
); );
final Map<String, dynamic> body = {}; final Map<String, dynamic> body = {};
// if (interests != null) body[ModelKey.userInterests] = interests.toString(); // if (interests != null) body[ModelKey.userInterests] = interests.toString();

@ -22,24 +22,11 @@ class SubscriptionAppIds {
return null; return null;
} }
factory SubscriptionAppIds.fromJson(json) { factory SubscriptionAppIds.fromJson(Map<String, dynamic> json) {
final SubscriptionAppIds appIds = SubscriptionAppIds(); return SubscriptionAppIds()
for (final appInfo in (json['items'] as List<dynamic>)) { ..stripeId = json['stripe_id']
final String platform = appInfo['type']; ..androidId = json['android_id']
final String appId = appInfo['id']; ..appleId = json['apple_id'];
switch (platform) {
case 'stripe':
appIds.stripeId = appId;
continue;
case 'app_store':
appIds.appleId = appId;
continue;
case 'play_store':
appIds.androidId = appId;
continue;
}
}
return appIds;
} }
} }

Loading…
Cancel
Save