TVOS FileManager's createFile fails with error 1 - file

I'm trying to create a json file on a Apple TV device to save some data but createFile(...) always fails, returning false. I've tried with absolutePath, relativePath and path to no success. The jsonData variable is created just fine in my implementation and it works on the Simulator:
self.fileName = "MyFileTest"
self.directory = .documentDirectory
let documentsDirectory = fileManager.urls(for: self.directory, in: .userDomainMask)[0]
self.fullyQualifiedPath = documentsDirectory.appendingPathComponent(self.fileName).appendingPathExtension("json").path
do {
let jsonData = try convertObjectToData(data: dataForJson)
if !fileManager.createFile(atPath: fullyQualifiedPath, contents: jsonData as Data, attributes: nil) {
print("File Manager failed at createFile")
throw FileErrors.FileNotSaved
}
} catch {
print("Unable to create json file \(error.localizedDescription)")
throw FileErrors.FileNotSaved
}
Here createFile fails and returns false and the following is printed out:
File Manager failed at createFile Unable to create json file The
operation couldn’t be completed.
(TestAppTVOS.FileSaveHelper.(FileErrors in
_70D0A1275AC2AFFFA4ED048E3A809030) error 1.)
The fullyQualifiedPath variable value is:
/var/mobile/Containers/Data/Application/00DCB709-5EC6-40FC-BB21-D797EB4FE2F5/Documents/MyFileTest.json
Not sure what to make out of that error message "The operation couldn’t be completed" and "error 1"? Any ideas how to get this working properly for Swift 3?

After spending a bit too much time on this it seems it was related to which folder I was creating the file in.
As I am in sandbox mode/debugging I could not write to the Documents folder so instead had to switch to the Cache folder.
E.g
self.directory = .cachesDirectory
Works now.

Related

The storage file is not properly formatted (Unexpected end of JSON) discord.js

I'm working on a giveaway bot and got that error. This is the full error
(node:4) UnhandledPromiseRejectionWarning: SyntaxError: The storage file is not properly formatted (Unexpected end of JSON input).
at GiveawaysManager.getAllGiveaways (/app/node_modules/discord-giveaways/src/Manager.js:308:27)
at async GiveawaysManager._init (/app/node_modules/discord-giveaways/src/Manager.js:391:30)
Here is my code:
const { GiveawaysManager } = require("discord-giveaways");
const manager = new GiveawaysManager(bot, {
storage: "./giveaways.json",
updateCountdownEvery: 10000,
default: {
botsCanWin: false,
embedColor: "#FF0000",
reaction: "🎉"
}
})
bot.giveawaysManager = manager;
}
})
I'm new to coding so it wil be great if you explain in baby steps
I had this same issue, and it turns out that the giveaways.json file only had a [] in it.
It is best if you just don't add a file because the module should add one for you!
The storage file is your ./giveaways.json. As seen in the npm documentation, it saves the file in JSON format which is highly likely to go wrong, make sure that you haven't touched the giveaways.json file, much less change it. Adding even a single line in the giveaways.json file may cause the GiveawaysManager to append wrongly and not be able to read it.
My suggestion is basically delete the ./giveaways.json file. This should refresh the file and be rid of all syntax errors unless it was from the npm module itself. Note that deleting it, will delete and therefore, stop all the giveaways in process, so make sure you have no giveaways in progress.
If this doesn't fix the issue, then delete the ./giveaways.json file again, and create a new ./giveaways.json file with this as it's contents:
{}

Opening a newly created File in Dart

I am new to dart and am currently trying to create a file from a data String.
All looks good so far as the length is not 0. But when i open the file, it instantly closes again, no console output, no errors.
I'd appreciate any pointers in the right direction, if any information is missing, please point it out and i will provide if possible.
void createFile(data) async{
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = new File(tempPath+widget.tileText);
var sink = file.openWrite();
sink.write(data.codeUnits);
await sink.flush();
await sink.close();
print(await file.length());
OpenFile.open(file.path);
}
UPDATE: added flush() and await before close() - loading a little smoother now, but File still closes instantly
Update2: removed create() (was a misunderstanding on my part)
now getting console output when the File closes: D/EGL_emulation(23235): eglCreateContext: 0xef02d650: maj 2 min 0 rcv 2
Running i ton my phone gives no console log, instead a simple "Can't open File" from the viewing application,i doublechecked the Path, it looks ok and it exists
So i found 2 problems and solved it now:
The path was missing a "/"
I didn't format the data right, i had to decode it and use writeAsBytes(), ditched the sink
now it's working
void createFile(data) async{
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = new File(tempPath+"/"+widget.tileText);
await file.writeAsBytes(base64Decode(data));
print(await file.length());
OpenFile.open(file.path);
print(await tempDir.exists());
print(file.path);
}

Google App Engine - Mail() attachment

I can successfully send emails with App Engine Mail API, but i cannot find the problem for why the attachment do not get attached in email. My code looks like this:
// Pull in the raw file data of the image file to attach it to the message.
$image_data = fopen('gs://pro-sitemaps-api/file.csv');
try {
$message = new Message();
$message->setSender('myemail#****.com');
$message->addTo('myemail#****.com');
$message->setSubject('Subject Google App Engine Test');
$message->setTextBody('Test body');
$message->addAttachment('file.csv', $image_data);
$message->send();
echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
echo 'There was an error'.$e;
}
My file is hosted in Google Storage (bucket). The filetype of storage file is .csv
Can anyone tell me what i am doing wrong?
Edit:
Adding "mode":"r" gives me this error:
$image_data = fopen('gs://pro-sitemaps-api/file.csv', 'r');
Output:
error: {
code: "500",
message: "An error occurred parsing (locally or remotely) the arguments to mail.Send().",
status: "UNKNOWN",
details: [ ]
}
}
Edit:
This works but this only sends the top line (header). not all lines. Tried adding this inside a array and send the array as attachment but then i get same error.:
$fpmail = fopen('gs://pro-sitemaps-api/file.csv', 'r');
//$attach = fread($fpmail);
$attach = fgets($fpmail);
print_r($attach);
try {
$message = new Message();
$message->setSender('asim#redperformance.no');
$message->addTo('asim#redperformance.no');
$message->setSubject('Test');
$message->setTextBody('Test nyeste');
$message->addAttachment('file.csv', $attach);
$message->send();
echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
echo $e;
}
fclose($fpmail);
I don't ever code in PHP, but it looks like you are not actually reading the contents of the file.
In most programming languages, a call like fopen is just the first step of getting the contents of the file, but doesn't actually get the contents. You'll probably need something like this:
$f = fopen('gs://pro-sitemaps-api/file.csv', 'r');
$image_data = $f.read();
but you'll need to figure out how to read data from a file in PHP.

Unable to open remote file in Word Online

I am trying to open a base64 encoded file in Word Online, using the code below based on .
function displayContents(myBase64) {
Word.run(function (context) {
console.log(Office.context.requirements.isSetSupported("WordApi", "1.1"));
// Create a proxy object for the document.
var thisDocument = context.document;
// Queue a command to clear the body contents.
thisDocument.body.clear();
thisDocument.body.insertFileFromBase64(myBase64, "replace");
// Create a proxy object for the default selection.
//var mySelection = thisDocument.getSelection();
// Queue a command to insert the file into the current document.
//mySelection.insertFileFromBase64(myBase64, "replace");
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync();
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
}
This does not work (using body.insertFileFromBase64 or myselection.insertFileFromBase64). The code does function in the regular version of Word. I receive the following error:
Error:
"name":"OfficeExtension.Error",
"code":"GeneralException",
"message":"This browser does not support the requested API.",
"traceMessages":[],"debugInfo":{}}
LoadOfficeDoc.js:51 Debug info: {}
Office.context.requirements.isSetSupported("WordApi", "1.1") returns true.
Am I doing something wrong or is this functionality not available online?
The new Word API (e.g. anything using Word.run) is presently only supported in Word 2016 on Windows (and iPad?)
Though according to the documentation isSetSupported should be returning false.
That's correct, this is actually a bug we are working on right now.
That requirement set is not full supported on WAC hence the method must return false.

Unable to upload multiple files to Google drive using PHP SDK

I am trying to upload multiple files to Google drive using the PHP SDK. For this I am calling the function below iteratively passing the required parameters:
function insertFile($driveService, $title, $description, $parentId, $fileUrl) {
global $header;
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$mimeType= "application/vnd.google-apps.folder";
if ($fileUrl != null) {
$fileUrl = replaceSpaceWithHtmlCode($fileUrl);
$header = getUrlHeader($fileUrl);
$mimeType = $header['content-type'];
}
$file->setMimeType($mimeType);
$parent = new Google_ParentReference();
// Set the parent folder.
if ($parentId != null) {
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = null;
if ($fileUrl != null) {
if (hasErrors($driveService, $fileUrl) == True) {
return null;
}
$data = file_get_contents($fileUrl);
}
$createdFile = $driveService->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (Exception $e) {
echo "Error: 12";
return null;
}
}
I am running this app on the Google App Engine.
However, I am unable to upload all the files I pass to it. For example, if I pass about 12-15 files, only 10-11 get uploaded, and sometimes all get uploaded, even though all parameters are correct. I have caught the exception when it fails to create a file and this says it is unable to create a file, for the files that are not uploaded. I don't see any warnings or errors in the logs on the app engine.
Am I missing something? Can someone please point me where I should be looking to correct this and make it reliable enough to upload all files given to it?
The HTTP response that I get when I try to upload 30 files is this:
PHP Fatal error: The request was aborted because it exceeded the maximum execution time
Check the http response to see the detailed reason. It might be that you are hitting the throttle limit and getting a 403 rate limit response.

Resources