1/*
2 * Copyright 2020, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Stephan A��mus <superstippi@gmx.de>
7 */
8
9
10#include "FetchUtils.h"
11#include "string.h"
12
13#include <Entry.h>
14#include <Node.h>
15#include <TypeConstants.h>
16
17namespace BPackageKit {
18
19namespace BPrivate {
20
21
22#define DL_COMPLETE_ATTR "Meta:DownloadCompleted"
23
24
25/*static*/ bool
26FetchUtils::IsDownloadCompleted(const char* path)
27{
28	BEntry entry(path, true);
29	BNode node(&entry);
30	return IsDownloadCompleted(node);
31}
32
33
34/*static*/ bool
35FetchUtils::IsDownloadCompleted(const BNode& node)
36{
37    bool isComplete;
38    status_t status = _GetAttribute(node, DL_COMPLETE_ATTR,
39        B_BOOL_TYPE, &isComplete, sizeof(isComplete));
40    if (status != B_OK) {
41        // Most likely cause is that the attribute was not written,
42        // for example by previous versions of the Package Kit.
43        // Worst outcome of assuming a partial download should be
44        // a no-op range request.
45        isComplete = false;
46    }
47    return isComplete;
48}
49
50
51/*static*/ status_t
52FetchUtils::MarkDownloadComplete(BNode& node)
53{
54    bool isComplete = true;
55    return _SetAttribute(node, DL_COMPLETE_ATTR,
56        B_BOOL_TYPE, &isComplete, sizeof(isComplete));
57}
58
59
60/*static*/ status_t
61FetchUtils::SetFileType(BNode& node, const char* type)
62{
63	return _SetAttribute(node, "BEOS:TYPE",
64        B_MIME_STRING_TYPE, type, strlen(type) + 1);
65}
66
67status_t
68FetchUtils::_SetAttribute(BNode& node, const char* attrName,
69    type_code type, const void* data, size_t size)
70{
71	if (node.InitCheck() != B_OK)
72		return node.InitCheck();
73
74	ssize_t written = node.WriteAttr(attrName, type, 0, data, size);
75	if (written != (ssize_t)size) {
76		if (written < 0)
77			return (status_t)written;
78		return B_IO_ERROR;
79	}
80	return B_OK;
81}
82
83
84status_t
85FetchUtils::_GetAttribute(const BNode& node, const char* attrName,
86    type_code type, void* data, size_t size)
87{
88	if (node.InitCheck() != B_OK)
89		return node.InitCheck();
90
91	ssize_t read = node.ReadAttr(attrName, type, 0, data, size);
92	if (read != (ssize_t)size) {
93		if (read < 0)
94			return (status_t)read;
95		return B_IO_ERROR;
96	}
97	return B_OK;
98}
99
100
101}	// namespace BPrivate
102
103}	// namespace BPackageKit
104