Deprecates the InputFile with PayloadId and replace the one with file path.

PiperOrigin-RevId: 440516892
This commit is contained in:
edwinwu
2022-04-08 21:44:01 -07:00
committed by Copybara-Service
parent 4c13db0c2d
commit 0c8838ad9b
10 changed files with 9 additions and 249 deletions
@@ -27,7 +27,6 @@ objc_library(
"Source/Internal/GNCPayload.mm",
"Source/Internal/GNCPayloadListener.mm",
"Source/Internal/GNCUtils.mm",
"Source/Internal/platform.mm",
],
hdrs = [
"Source/Internal/GNCCore.h",
@@ -18,7 +18,6 @@
#include "connections/core.h"
#include "connections/implementation/service_controller_router.h"
#include "internal/platform/payload_id.h"
NS_ASSUME_NONNULL_BEGIN
@@ -30,23 +29,6 @@ NS_ASSUME_NONNULL_BEGIN
_service_controller_router;
}
/**
* These functions are the utilities to manipulate the InputFile in ImplementationPlatform for
* sending File payload.
*
* Inserts the URL to the map, keyed by payloadID. The element will not be inserted if there
* already is an element with the key in the map.
*/
- (void)insertURLToMapWithPayloadID:(::location::nearby::PayloadId)payloadId urlToSend:(NSURL *)url;
/**
* Returns the URL with the payloadID and removes the entry from the map. Returns nil if
* payloadID is not found.
*/
- (nullable NSURL *)extractURLWithPayloadID:(::location::nearby::PayloadId)payloadId;
- (void)clearSendingURLMaps;
@end
/** This function returns the Core singleton, wrapped in an Obj-C object for lifetime management. */
@@ -16,21 +16,15 @@
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/internal/common.h"
#include "connections/core.h"
#include "connections/implementation/service_controller_router.h"
#include "internal/platform/payload_id.h"
#import "GoogleToolboxForMac/GTMLogger.h"
using ::location::nearby::connections::Core;
using ::location::nearby::PayloadId;
using ::location::nearby::connections::ServiceControllerRouter;
@implementation GNCCore {
// A map to store the NSURL object with PayloadId for sendFilePayload in GNCConnection.
// This is the place to store the NSURL for InputFile creation in ImplementationPlatform.
absl::flat_hash_map<PayloadId, NSURL *> _sending_urls;
}
- (instancetype)init {
@@ -49,24 +43,6 @@ using ::location::nearby::connections::ServiceControllerRouter;
GTMLoggerInfo(@"GNCCore deallocated");
}
- (void)insertURLToMapWithPayloadID:(PayloadId)payloadId urlToSend:(NSURL *)url {
_sending_urls.emplace(payloadId, url);
}
- (nullable NSURL *)extractURLWithPayloadID:(PayloadId)payloadId {
NSURL *url;
auto it = _sending_urls.find(payloadId);
if (it != _sending_urls.end()) {
auto pair = _sending_urls.extract(it);
url = pair.mapped();
}
return url;
}
- (void)clearSendingURLMaps {
_sending_urls.clear();
}
@end
GNCCore *GNCGetCore() {
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <utility>
#import "internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h"
#include "connections/core.h"
@@ -19,7 +21,6 @@
#include "internal/platform/exception.h"
#include "internal/platform/file.h"
#include "internal/platform/implementation/input_file.h"
#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
#import "internal/platform/implementation/ios/Source/Platform/utils.h"
#import "internal/platform/implementation/ios/Source/Public/NearbyConnections/GNCConnection.h"
#import "internal/platform/implementation/ios/Source/Public/NearbyConnections/GNCPayload.h"
@@ -159,9 +160,7 @@ class GNCInputStreamFromNSStream : public InputStream {
fileSize = fileSizeValue.longValue;
}
PayloadId payloadId = payload.identifier;
// Add the pair of payloadId and fileURL to the map in the GNCCore.
[_core insertURLToMapWithPayloadID:payloadId urlToSend:fileURL];
InputFile inputFile(payloadId, fileSize);
InputFile inputFile(CppStringFromObjCString(fileURL.path), fileSize);
Payload corePayload(payloadId, std::move(inputFile));
progress.totalUnitCount = fileSize;
return [self sendPayload:std::move(corePayload)
@@ -19,15 +19,14 @@ objc_library(
name = "Platform",
srcs = [
"crypto.mm",
"input_file.mm",
"log_message.mm",
"multi_thread_executor.mm",
"platform.mm",
"scheduled_executor.mm",
"utils.mm",
"wifi_lan.mm",
],
hdrs = [
"input_file.h",
"log_message.h",
"multi_thread_executor.h",
"scheduled_executor.h",
@@ -1,54 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PLATFORM_IMPL_IOS_INPUT_FILE_H_
#define PLATFORM_IMPL_IOS_INPUT_FILE_H_
#import <Foundation/Foundation.h>
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/input_file.h"
namespace location {
namespace nearby {
namespace ios {
/** This InputFile subclass takes input from an NSURL. */
class InputFile : public api::InputFile {
public:
explicit InputFile(NSURL *nsURL);
explicit InputFile(absl::string_view file_path, std::int64_t size);
~InputFile() override = default;
InputFile(InputFile &&) = default;
InputFile &operator=(InputFile &&) = default;
ExceptionOr<ByteArray> Read(std::int64_t size) override;
std::string GetFilePath() const override;
std::int64_t GetTotalSize() const override;
Exception Close() override;
private:
NSURL *nsURL_;
NSInputStream *nsStream_;
std::string path_;
size_t total_size_;
};
} // namespace ios
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_IOS_INPUT_FILE_H_
@@ -1,74 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "internal/platform/implementation/ios/Source/Platform/input_file.h"
#include <string>
#import "internal/platform/exception.h"
#import "internal/platform/implementation/ios/Source/Platform/utils.h"
namespace location {
namespace nearby {
namespace ios {
InputFile::InputFile(NSURL *nsURL) : nsURL_(nsURL) {
std::string string = CppStringFromObjCString([nsURL_ absoluteString]);
nsStream_ = [NSInputStream inputStreamWithURL:nsURL_];
[nsStream_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[nsStream_ open];
}
InputFile::InputFile(absl::string_view file_path, std::int64_t size)
: path_(file_path), total_size_(size) {
// TODO(jfcarroll): This is not implemented for iOS yet.
}
ExceptionOr<ByteArray> InputFile::Read(std::int64_t size) {
uint8_t *bytes_read = new uint8_t[size];
NSUInteger numberOfBytesToRead = [[NSNumber numberWithLongLong:size] unsignedIntegerValue];
NSInteger numberOfBytesRead = [nsStream_ read:bytes_read maxLength:numberOfBytesToRead];
if (numberOfBytesRead == 0) {
// Reached end of stream.
return ExceptionOr<ByteArray>();
} else if (numberOfBytesRead < 0) {
// Stream error.
return ExceptionOr<ByteArray>(Exception::kIo);
}
return ExceptionOr<ByteArray>(ByteArrayFromNSData([NSData dataWithBytes:bytes_read
length:numberOfBytesRead]));
}
std::string InputFile::GetFilePath() const {
return CppStringFromObjCString([nsURL_ absoluteString]);
}
std::int64_t InputFile::GetTotalSize() const {
NSNumber *fileSizeValue = nil;
BOOL result = [nsURL_ getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:nil];
if (result) {
return fileSizeValue.longValue;
} else {
return 0;
}
}
Exception InputFile::Close() {
[nsStream_ close];
return {Exception::kSuccess};
}
} // namespace ios
} // namespace nearby
} // namespace location
@@ -16,12 +16,10 @@
#include <string>
#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
#include "internal/platform/implementation/ios/Source/Platform/atomic_boolean.h"
#include "internal/platform/implementation/ios/Source/Platform/atomic_uint32.h"
#include "internal/platform/implementation/ios/Source/Platform/condition_variable.h"
#include "internal/platform/implementation/ios/Source/Platform/count_down_latch.h"
#include "internal/platform/implementation/ios/Source/Platform/input_file.h"
#import "internal/platform/implementation/ios/Source/Platform/log_message.h"
#import "internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h"
#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
@@ -42,11 +40,12 @@ std::string ImplementationPlatform::GetDownloadPath(std::string& parent_folder,
// TODO(jfcarroll): This needs to be done correctly, we now have a file name and parent folder,
// they should be combined with the default download path
NSString* fileName = ObjCStringFromCppString(file_name);
NSError* error = nil;
NSURL* downloadsURL = [[NSFileManager defaultManager] URLForDirectory:NSDownloadsDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:nil];
error:&error];
// TODO(b/227535777): If file name matches an existing file, it will be overwritten. Append a number until
// a unique file name is reached 'foobar (2).png'.
return CppStringFromObjCString([downloadsURL URLByAppendingPathComponent:fileName].path);
@@ -85,18 +84,9 @@ std::unique_ptr<ConditionVariable> ImplementationPlatform::CreateConditionVariab
ABSL_DEPRECATED("This interface will be deleted in the near future.")
std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(PayloadId payload_id,
std::int64_t total_size) {
// Extract the NSURL object with payload_id from |GNCCore| which stores the maps. If the retrieved
// NSURL object is not nil, we create InputFile by ios::InputFile. The difference is
// that ios::InputFile implements to read bytes from local real file for sending.
GNCCore* core = GNCGetCore();
NSURL* url = [core extractURLWithPayloadID:payload_id];
if (url != nil) {
return std::make_unique<ios::InputFile>(url);
} else {
std::string parent_folder("");
std::string file_name(std::to_string(payload_id));
return shared::IOFile::CreateInputFile(GetDownloadPath(parent_folder, file_name), total_size);
}
std::string parent_folder("");
std::string file_name(std::to_string(payload_id));
return shared::IOFile::CreateInputFile(GetDownloadPath(parent_folder, file_name), total_size);
}
std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(absl::string_view file_path,
@@ -22,7 +22,6 @@ objc_library(
testonly = 1,
srcs = [
"Platform/GNCCryptoTest.mm",
"Platform/GNCInputFileTest.mm",
"Platform/GNCMultiThreadExecutorTest.mm",
"Platform/GNCScheduledExecutorTest.mm",
"Platform/GNCSingleThreadExecutorTest.mm",
@@ -1,56 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <XCTest/XCTest.h>
#import "internal/platform/byte_array.h"
#import "internal/platform/exception.h"
#import "internal/platform/implementation/ios/Source/Platform/input_file.h"
using ::location::nearby::ios::InputFile;
using ::location::nearby::ByteArray;
using ::location::nearby::ExceptionOr;
@interface GNCInputFileTest : XCTestCase
@end
@implementation GNCInputFileTest
// TODO(b/169292092): Find more tools (e.g. file/util/TempPath) to test fake file.
- (void)testNonExistentPath {
std::string cc_path("/foo/bar/test.ext");
NSString* objcPath = [NSString stringWithUTF8String:cc_path.c_str()];
NSURL *testURL = [NSURL URLWithString:objcPath];
auto input_file = std::make_unique<InputFile>(testURL);
XCTAssert(input_file != nullptr);
XCTAssertEqual(input_file->GetTotalSize(), 0);
ExceptionOr<ByteArray> read_result = input_file->Read(3);
XCTAssertFalse(read_result.ok());
}
- (void)testGetFilePath {
std::string cc_path("/foo/bar/test.ext");
NSString* objcPath = [NSString stringWithUTF8String:cc_path.c_str()];
NSURL *testURL = [NSURL URLWithString:objcPath];
auto input_file = std::make_unique<InputFile>(testURL);
XCTAssert(input_file != nullptr);
std::string input_file_path = input_file->GetFilePath();
XCTAssertTrue([objcPath isEqualToString:[NSString stringWithUTF8String:input_file_path.c_str()]]);
}
@end