Debian Codegraph @

extra/haxelib_src/src/website/api/ProjectApi.hx

raw
1 package website.api;
2
3 import haxe.io.Bytes;
4 import haxe.zip.Entry;
5 import haxe.zip.Reader;
6 import haxelib.Data;
7 import haxelib.server.FileStorage;
8 import haxelib.server.Repo;
9 import haxelib.server.Paths.*;
10 import ufront.api.UFApi;
11 import ufront.cache.UFCache;
12 import ufront.web.HttpError;
13 import website.model.SiteDb;
14 import haxe.ds.Option;
15 import sys.*;
16 import sys.io.*;
17 using tink.CoreApi;
18 using StringTools;
19 using haxe.io.Path;
20
21 class ProjectApi extends UFApi {
22
23 public static var cacheNames = {
24 info: 'haxelib_zip_cache_info',
25 dirListing: 'haxelib_zip_cache_dir_list',
26 fileBytes: 'haxelib_zip_cache_file_content'
27 };
28
29 // TODO: inject the repo directory instead.
30 @inject("scriptDirectory") public var scriptDir:String;
31 @inject public var cacheCnx:UFCacheConnectionSync;
32
33 /** Extensions that should be loaded as a text file. **/
34 public static var textExtensions:Array<String> = ["md","txt","hx","hxml","json","xml","htaccess","yml","gitignore","conf","html","mtt","htm","js","css","less","scss"];
35 public static var imgExtensions:Array<String> = ["jpg","jpeg","gif","png","svg","ico"];
36
37 /**
38 Load the ProjectInfos for the given project.
39 This contains basic metadata and is loaded from the database (though it is set via a haxelib.json file during project upload).
40 **/
41 public function projectInfo( projectName:String ):Outcome<ProjectInfos,Error> {
42 try {
43 var info = new Repo().infos(projectName);
44 return Success( info );
45 }
46 catch ( e:Dynamic ) {
47 var error =
48 if ( Std.is(e,String) && StringTools.startsWith(e,"No such Project") ) HttpError.pageNotFound();
49 else Error.withData('Failed to get info for project $projectName',e);
50 return Failure( error );
51 }
52 }
53
54 /**
55 Given a path, load either the file or the directory listing, and take a guess at the content type.
56
57 This will use `this.cacheCnx` to cache results, to prevent us having to load the zip file each time.
58 **/
59 public function getInfoForPath( projectName:String, version:String, path:String ):Outcome<FileInformation,Error> {
60 try {
61 var pathWithSlash = path.addTrailingSlash();
62 var cache = cacheCnx.getNamespaceSync( cacheNames.info );
63 var fileInfo = cache.getOrSetSync( '$projectName:$version:$pathWithSlash', function() {
64 var extension = path.extension();
65 var zip = getZipEntries(projectName,version);
66 var fileInfo = null;
67 for ( entry in zip ) {
68 if ( entry.fileName==path ) {
69 // Exact match! It's a file, not a directory. Now, check the type and load it.
70 fileInfo =
71 if ( textExtensions.indexOf(extension)>-1 )
72 Text( Reader.unzip(entry).toString(), extension, entry.fileSize );
73 else if ( imgExtensions.indexOf(extension)>-1 )
74 Image( Reader.unzip(entry), extension, entry.fileSize );
75 else
76 Binary( entry.fileSize );
77 break;
78 }
79 else if ( entry.fileName==pathWithSlash || pathWithSlash=="/" ) {
80 // It's a directory, so get the listing of files and sub directories.
81 var dirListing = getDirListing( zip, path );
82 fileInfo = Directory( dirListing.dirs, dirListing.files );
83 break;
84 }
85 }
86 if (fileInfo == null) {
87 // If it's still null, handle one more case: there's no zip entry for the requested directory,
88 // but there are entries for files in it. Get listing of that directory and if it's not empty,
89 // return it.
90 var dirListing = getDirListing( zip, path );
91 if (dirListing.dirs.length > 0 || dirListing.files.length > 0)
92 fileInfo = Directory( dirListing.dirs, dirListing.files );
93 }
94 return fileInfo;
95 }).sure();
96 return
97 if ( fileInfo!=null ) Success( fileInfo );
98 else Failure( HttpError.pageNotFound() );
99 }
100 catch ( e:Dynamic ) return Failure( Error.withData(
101 'Failed to get file information for $path in $projectName ($version)',
102 Std.string(e) + "\n" +
103 haxe.CallStack.toString(haxe.CallStack.exceptionStack())
104 ) );
105 }
106
107 /**
108 Fetch a list of files in a directory in the zip file.
109
110 This will use `this.cacheCnx` to cache results, to prevent us having to load the zip file each time.
111
112 Returns a Success with two arrays, containing a) sub directories, and b) files. Names are relative to the dirPath, not absolute to the zip.
113 Returns a Failure with an error if one is encountered.
114 **/
115 public function getDirListingFromZip( projectName:String, version:String, dirPath:String ):Outcome<{ dirs:Array<String>, files:Array<String> },Error> {
116 try {
117 var cache = cacheCnx.getNamespaceSync( cacheNames.dirListing );
118 var listing = cache.getOrSetSync( '$projectName:$version:$dirPath', function() {
119 var zip = getZipEntries(projectName,version);
120 return getDirListing(zip,dirPath);
121 }).sure();
122 return Success( listing );
123 }
124 catch ( e:Dynamic ) return Failure( Error.withData('Failed to read directory $dirPath from $projectName ($version) zip',e) );
125 }
126
127 /**
128 Read text content from a file in a project's zip file.
129 Returns Success(Some(contents)) if the file was read successfully.
130 Returns Success(None) if the file was not found in the zip file.
131 Returns Failure if an error was encountered.
132 **/
133 public function readContentFromZip( projectName:String, version:String, filename:String, ?caseSensitive:Bool=true ):Outcome<Option<String>,Error> {
134 // This is the same as readBytesFromZip, but we transform the result to turn Bytes into a String.
135 return readBytesFromZip( projectName, version, filename, caseSensitive ).map(function (outcome) return switch outcome {
136 case Some(bytes): Some( bytes.toString() );
137 case None: None;
138 });
139 }
140
141 /**
142 Read the raw bytes from a file in a project's zip file.
143 Returns Success(Some(bytes)) if the file was read successfully.
144 Returns Success(None) if the file was not found in the zip file.
145 Returns Failure if an error was encountered.
146 **/
147 public function readBytesFromZip( projectName:String, version:String, filename:String, ?caseSensitive:Bool=true ):Outcome<Option<Bytes>,Error> {
148 try {
149 var cache = cacheCnx.getNamespaceSync( cacheNames.fileBytes );
150 var bytes = cache.getOrSetSync( '$projectName:$version:$filename:$caseSensitive', function() {
151 var zip = getZipEntries( projectName, version );
152 return getBytesFromFile( zip, filename, caseSensitive );
153 }).sure();
154 return
155 if ( bytes!=null ) Success( Some(bytes) );
156 else Success( None );
157 }
158 catch ( e:Dynamic ) return Failure( Error.withData('Failed to read $filename from $projectName ($version) zip: $e',e) );
159 }
160
161 /**
162 Get the path to the zip file (relative to the script directory).
163 **/
164 public function getZipFilePath( project:String, version:String ):String {
165 return Path.join([REP_DIR_NAME, Data.fileName(project, version)]);
166 }
167
168 //
169 // Private API
170 //
171
172 /** Get a list of entries in a zip file. **/
173 function getZipEntries( projectName:String, version:String ):List<Entry> {
174 return FileStorage.instance.readFile(
175 getZipFilePath( projectName, version ),
176 function(path) {
177 var file = File.read(path, true);
178 var zip = try {
179 haxe.zip.Reader.readZip(file);
180 } catch( e : Dynamic ) {
181 file.close();
182 neko.Lib.rethrow(e);
183 };
184 file.close();
185 return zip;
186 }
187 );
188 }
189
190 /** Attempt to extract the bytes of a file within a zip file. Will return null if the file was not found. **/
191 function getBytesFromFile( zip:List<Entry>, filename:String, caseSensitive:Bool ):Null<Bytes> {
192 var file = null;
193 for( f in zip ) {
194 var sameName = f.fileName==filename || (caseSensitive==false && f.fileName.toLowerCase()==filename.toLowerCase());
195 if ( sameName )
196 return Reader.unzip( f );
197 }
198 return null;
199 }
200
201 /** Get a directory listing from the zip entries. If the directory doesn't exist the file listings will just be empty. **/
202 function getDirListing( zip:List<Entry>, dirPath:String ):{ dirs:Array<String>, files:Array<String> } {
203 dirPath = dirPath.addTrailingSlash();
204 var subdirectories = [];
205 var files = [];
206 for( f in zip ) {
207 var fileInsideDirectory = (f.fileName.startsWith(dirPath) && f.fileName.length>dirPath.length) || dirPath=="/";
208 if ( fileInsideDirectory ) {
209 var remainingName =
210 if ( dirPath=="/" ) f.fileName;
211 else f.fileName.substr( dirPath.length );
212 if ( remainingName.indexOf('/')==-1 ) {
213 // This is a file in this directory. Add it if we don't have it already.
214 if ( files.indexOf(remainingName)==-1 )
215 files.push( remainingName );
216 }
217 else {
218 // This is a file in a subdirectory. Add it if we don't have it already.
219 var subdirName = remainingName.substr( 0, remainingName.indexOf('/') );
220 if ( subdirectories.indexOf(subdirName)==-1 )
221 subdirectories.push( subdirName );
222 }
223 }
224 }
225 return { dirs:subdirectories, files:files };
226 }
227 }
228
229 /**
230 A description of a file found in a Haxelib zip file.
231 **/
232 enum FileInformation {
233 /** A text file, with it's String content and extension. **/
234 Text( content:String, extension:String, size:Int );
235 /** A text file, with it's Bytes content and extension. **/
236 Image( content:Bytes, extension:String, size:Int );
237 /** A binary file that we can't display, together with it's size. **/
238 Binary( size:Int );
239 /** A directory listing, with separate arrays for subdirs and files. **/
240 Directory( subdirs:Array<String>, files:Array<String> );
241 }