From 5c5c0db79232b3812127c26d6d15438db86e6852 Mon Sep 17 00:00:00 2001 From: Eric Rozell Date: Wed, 23 Aug 2017 21:08:56 -0400 Subject: [PATCH] Adds react-native-windows support for UWP This changeset includes most of the react-native-fs functionality working for UWP. Some notable missing features are: * all of the `Assets` APIs (e.g., `readDirAssets`, `existsAssets`, etc.) that are Android specific * the `pathForBundle` and `pathForGroup` APIs that are iOS specific * the `uploadFiles` API, which just has not yet been implemented. --- windows/.gitignore | 78 + windows/.npmignore | 9 + .../Assets/LockScreenLogo.scale-200.png | Bin 0 -> 1430 bytes .../Assets/SplashScreen.scale-200.png | Bin 0 -> 7700 bytes .../Assets/Square150x150Logo.scale-200.png | Bin 0 -> 2937 bytes .../Assets/Square44x44Logo.scale-200.png | Bin 0 -> 1647 bytes ...x44Logo.targetsize-24_altform-unplated.png | Bin 0 -> 1255 bytes windows/RNFS.Tests/Assets/StoreLogo.png | Bin 0 -> 1451 bytes .../Assets/Wide310x150Logo.scale-200.png | Bin 0 -> 3204 bytes windows/RNFS.Tests/Package.appxmanifest | 45 + windows/RNFS.Tests/Properties/AssemblyInfo.cs | 18 + .../RNFS.Tests/Properties/UnitTestApp.rd.xml | 29 + windows/RNFS.Tests/RNFS.Tests.csproj | 151 ++ windows/RNFS.Tests/RNFS.Tests.nuget.props | 18 + windows/RNFS.Tests/RNFS.Tests.nuget.targets | 9 + .../RNFS.Tests/RNFS.Tests_TemporaryKey.pfx | Bin 0 -> 2512 bytes windows/RNFS.Tests/RNFSManagerTests.cs | 1632 +++++++++++++++++ windows/RNFS.Tests/UnitTestApp.xaml | 8 + windows/RNFS.Tests/UnitTestApp.xaml.cs | 102 ++ windows/RNFS.Tests/project.json | 18 + windows/RNFS.sln | 120 ++ windows/RNFS/Properties/AssemblyInfo.cs | 31 + windows/RNFS/Properties/RNFS.rd.xml | 28 + windows/RNFS/RNFS.csproj | 153 ++ windows/RNFS/RNFSManager.cs | 645 +++++++ windows/RNFS/RNFSPackage.cs | 53 + windows/RNFS/project.json | 16 + 27 files changed, 3163 insertions(+) create mode 100644 windows/.gitignore create mode 100644 windows/.npmignore create mode 100644 windows/RNFS.Tests/Assets/LockScreenLogo.scale-200.png create mode 100644 windows/RNFS.Tests/Assets/SplashScreen.scale-200.png create mode 100644 windows/RNFS.Tests/Assets/Square150x150Logo.scale-200.png create mode 100644 windows/RNFS.Tests/Assets/Square44x44Logo.scale-200.png create mode 100644 windows/RNFS.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png create mode 100644 windows/RNFS.Tests/Assets/StoreLogo.png create mode 100644 windows/RNFS.Tests/Assets/Wide310x150Logo.scale-200.png create mode 100644 windows/RNFS.Tests/Package.appxmanifest create mode 100644 windows/RNFS.Tests/Properties/AssemblyInfo.cs create mode 100644 windows/RNFS.Tests/Properties/UnitTestApp.rd.xml create mode 100644 windows/RNFS.Tests/RNFS.Tests.csproj create mode 100644 windows/RNFS.Tests/RNFS.Tests.nuget.props create mode 100644 windows/RNFS.Tests/RNFS.Tests.nuget.targets create mode 100644 windows/RNFS.Tests/RNFS.Tests_TemporaryKey.pfx create mode 100644 windows/RNFS.Tests/RNFSManagerTests.cs create mode 100644 windows/RNFS.Tests/UnitTestApp.xaml create mode 100644 windows/RNFS.Tests/UnitTestApp.xaml.cs create mode 100644 windows/RNFS.Tests/project.json create mode 100644 windows/RNFS.sln create mode 100644 windows/RNFS/Properties/AssemblyInfo.cs create mode 100644 windows/RNFS/Properties/RNFS.rd.xml create mode 100644 windows/RNFS/RNFS.csproj create mode 100644 windows/RNFS/RNFSManager.cs create mode 100644 windows/RNFS/RNFSPackage.cs create mode 100644 windows/RNFS/project.json diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 00000000..cbf7e7f4 --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,78 @@ +*AppPackages* +*BundleArtifacts* +*ReactAssets* + +#OS junk files +[Tt]humbs.db +*.DS_Store + +#Visual Studio files +*.[Oo]bj +*.user +*.aps +*.pch +*.vspscc +*.vssscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.[Cc]ache +*.ilk +*.log +*.lib +*.sbr +*.sdf +*.opensdf +*.opendb +*.unsuccessfulbuild +ipch/ +[Oo]bj/ +[Bb]in +[Dd]ebug*/ +[Rr]elease*/ +Ankh.NoLoad + +#MonoDevelop +*.pidb +*.userprefs + +#Tooling +_ReSharper*/ +*.resharper +[Tt]est[Rr]esult* +*.sass-cache + +#Project files +[Bb]uild/ + +#Subversion files +.svn + +# Office Temp Files +~$* + +# vim Temp Files +*~ + +#NuGet +packages/ +*.nupkg + +#ncrunch +*ncrunch* +*crunch*.local.xml + +# visual studio database projects +*.dbmdl + +#Test files +*.testsettings + +#Other files +*.DotSettings +.vs/ +*project.lock.json diff --git a/windows/.npmignore b/windows/.npmignore new file mode 100644 index 00000000..dd626ca0 --- /dev/null +++ b/windows/.npmignore @@ -0,0 +1,9 @@ + +# Make sure we don't publish build artifacts to NPM +ARM/ +Debug/ +x64/ +x86/ +bin/ +obj/ +.vs/ diff --git a/windows/RNFS.Tests/Assets/LockScreenLogo.scale-200.png b/windows/RNFS.Tests/Assets/LockScreenLogo.scale-200.png new file mode 100644 index 0000000000000000000000000000000000000000..735f57adb5dfc01886d137b4e493d7e97cf13af3 GIT binary patch literal 1430 zcmaJ>TTC2P7~aKltDttVHYH6u8Io4i*}3fO&d$gd*bA_<3j~&e7%8(eXJLfhS!M@! zKrliY>>6yT4+Kr95$!DoD(Qn-5TP|{V_KS`k~E6(LGS@#`v$hQo&^^BKsw3HIsZBT z_y6C2n`lK@apunKojRQ^(_P}Mgewt$(^BBKCTZ;*xa?J3wQ7~@S0lUvbcLeq1Bg4o zH-bvQi|wt~L7q$~a-gDFP!{&TQfc3fX*6=uHv* zT&1&U(-)L%Xp^djI2?~eBF2cxC@YOP$+9d?P&h?lPy-9M2UT9fg5jKm1t$m#iWE{M zIf%q9@;fyT?0UP>tcw-bLkz;s2LlKl2qeP0w zECS7Ate+Awk|KQ+DOk;fl}Xsy4o^CY=pwq%QAAKKl628_yNPsK>?A>%D8fQG6IgdJ ztnxttBz#NI_a@fk7SU`WtrpsfZsNs9^0(2a z@C3#YO3>k~w7?2hipBf{#b6`}Xw1hlG$yi?;1dDs7k~xDAw@jiI*+tc;t2Lflg&bM)0!Y;0_@=w%`LW^8DsYpS#-bLOklX9r?Ei}TScw|4DbpW%+7 zFgAI)f51s}{y-eWb|vrU-Ya!GuYKP)J7z#*V_k^Xo>4!1Yqj*m)x&0L^tg3GJbVAJ zJ-Pl$R=NAabouV=^z_t;^K*0AvFs!vYU>_<|I^#c?>>CR<(T?=%{;U=aI*SbZADLH z&(f2wz_Y0??Tf|g;?|1Znw6}6U43Q#qNRwv1vp9uFn1)V#*4p&%$mP9x&15^OaBiDS(XppT|z^>;B{PLVEbS3IFYV yGvCsSX*m literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/SplashScreen.scale-200.png b/windows/RNFS.Tests/Assets/SplashScreen.scale-200.png new file mode 100644 index 0000000000000000000000000000000000000000..023e7f1feda78d5100569825acedfd213a0d84e9 GIT binary patch literal 7700 zcmeHLYj~4Yw%(;oxoEH#Kxq-eR|+VkP17b#Vk;?4QwkI+A{L04G+#<<(x#Un1#+h5>eArRq zTw$)ZvTWW_Y?bDho0nPVTh08+s`sp!j74rJTTtXIDww0SILedFv?sZ?yb@@}GN;#8 znk_b~Q(A0YR#uV4ef!osoV1M3;vQ8N$O|fStfgf$S5;ddUNv`tWtGjM;koG#N;7M< zP*84lnx(bn_KF&9Z5Ai$)#Cs3a|$OFw>WKCT$of*L7_CqQEinflT|W{JT+aKp-E0v zsxmYg)1(T>DROm+LN1eQw8}KCTp=C!$H7`PU!t9_Hw@TsTI2`udRZv*!a5`#A9hK6Y95L(CDUX&_@QxKV z_feX{UhA#ZWlvgpL$#w^D#lq`_A4AzDqd|Zv6y9PX&DNcN|l}_D^{q@GG&H^Pg583 z8FI6N8^H7b5WjGp;urW)d7F+_lcp%KsLX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Rz&?6$Rypj{xO!`y=*J5o4@U8Q-(y5(*=YoKeZ+-1YdljXxkA#B)zo=FeQH#?Le zycNUmEEHWO9a=X^pb#&cOq7-`7UA87#|S22)<7RUtZo|(zibX=w;K3qur9vy#`MNV z6UUcf9ZwEnKCCp+OoBnF@OdbvH)ANXO0o~Pi9l8=x3))}L<#vO0-~O4!~--Ket?d} zJaqsj<@CD1%S2cTW%rOP{Vto%0sGW~1RMa_j^)5nil0Yw- z0EE#bP+l4#P^%PQ+N*oxu1Zq05xZ!bXfYTg>9c{(Iw*lnjR^>kz%lAN^zFce7rppy zY8zA~3GD=A6d*hze&l4D_wA~+O!56)BZTe_rEu}Ezi<4!kG|W#amBZ5{&XS2@6R~H z{9o^y*BkH4$~yX9U&@CgbOzX1bn9xqF|zh$Dh0Y5y*E0e90*$!ObrHY3Ok0`2=O~r zCuke6KrP9KOf?V(YDsM<6pX2nVoN%M$LT^q#FmtaF?1^27F*IcNX~XRB(|hCFvdcc zc)$=S-)acdk$g4?_>jRqxpI6M3vHZk?0c^3=byamYDNf;uB{3NlKW5IhnOS3DNkMV z?tK8?kJ}pmvp%&&eTVOVjHP`q34hN1@!aK}H(K!vI`~gf|Gv+FNEQD5Yd<~yX7k_l h&G-K)@HZb3BABY{)U1?^%I#E6`MGoTtustd{~yM6srvu` literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/Square150x150Logo.scale-200.png b/windows/RNFS.Tests/Assets/Square150x150Logo.scale-200.png new file mode 100644 index 0000000000000000000000000000000000000000..af49fec1a5484db1d52a7f9b5ec90a27c7030186 GIT binary patch literal 2937 zcma)84OCO-8BSud5)jwMLRVKgX(S?$n?Ld|vrsm<$CF7)&zTbyy1FE5bU`Q17MRv`9ue$;R(@8kR;#vJ*IM0>cJIAOte!d7oRgdH zd%ySjdB6L9=gX^A6)VzH7p2l@v~3zJAMw|DFy#^)F@@F*`mqUn=Il>l)8_+ab;nOW{%+iPx z+s{Eu|&pIs)Z7{La9~?xKfyl z#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jRoZ4ozC3{O%@5?)XzH35zHns$pgU*Q?fj4v?fp1Qbm+j;3l;9jam9Da zXVcKjPlQ73x78QPu|Ffm6x?`~e3oD=gl=4kYK?={kD5j~QCXU)`HSdduNNENzA*2$ zOm3PzF!lN5e*06-f1Uot67wY#{o-S1!KZ7E=!~7ynnk9_iJR#kFoNbAOT#^2Gd17F zMmvU6>lndZQGd|ax9kUoXXO+$N?|j@6qpsF&_j7YXvwo_C{JpmLw5&#e6k>atv%es z5)7r*Wvv_JkUpT}M!_o!nVlEk1Zbl=a*2hQ*<|%*K1Glj^FcF`6kTzGQ3lz~2tCc@ z&x|tj;aH&1&9HwcJBcT`;{?a+pnej;M1HO(6Z{#J!cZA04hnFl;NXA+&`=7bjW_^o zfC40u3LMG?NdPtwGl>Tq6u}*QG)}-y;)lu-_>ee3kibW(69n0$0Zy!}9rQz%*v1iO zT9_H>99yIrSPYVy6^);rR}7Yo=J_T@hi+qhTZXnVWyf;JDYm5#eYLTxr*?kiNn!+Y zQ+LUkBafNJ#rH#C(?d5^;gw9o#%daEI{mA*LHPIHPU`#|H$hD zwm>0&+kahQ)E#%~k>&5@&#Vg82H?s%71=)(soi@174pi9--2{w{1$}Sz4zGn3Du&x bht0Iza^2ykEt4(epJ78uh5nDlX8(TxzDYwP literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/Square44x44Logo.scale-200.png b/windows/RNFS.Tests/Assets/Square44x44Logo.scale-200.png new file mode 100644 index 0000000000000000000000000000000000000000..ce342a2ec8a61291ba76c54604aea7e9d20af11b GIT binary patch literal 1647 zcmaJ?eM}Q)7(e+G1Q(|`V9JhTI2>MkceK4;p;PR&$Pi?ejk3YQ_3o`S&|W_dsOZ8# zWPTt69g`t$ab`0cj-Y0yiBSOqmd)tG7G(}M5aP0_%&9TijB#&)I{zSE^4@#z^FF`l z`8{8`o%wlL(UI|y2!cdsuVamHH~H86F!*-15em4)NqUpCQM5?aoC_eCf@lV4wvF2a zjDQn1JBL69f&@2M3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^wh{{!TZT%7;_ literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/windows/RNFS.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png new file mode 100644 index 0000000000000000000000000000000000000000..f6c02ce97e0a802b85f6021e822c89f8bf57d5cd GIT binary patch literal 1255 zcmaJ>TWs4@7*5+{G#S+&C!qC#> zf>5N3P6jO*Cz>ug*(_DmW=)kea&m$gZ^+nyiF`;j%w@}y8)>p*SH}C`m?DXeieF2U zyQHecc_L%Gh!7GMt+hG06y;+|p4>m~}PjA}rKViGiEnn7G0ZO<>G|7q;2?NwGCM3s?eued6%hd$B+ z*kQJ{#~$S=DFE(%=E+UkmlEI*%3llUf~8Ja9YU1Vui0IbGBkW_gHB%Rd&!!ioX zs40O?i9I{};kle7GMvE7(rk`la=gTI)47=>%?q@^iL-nUo3}h4S}N-KHn8t5mVP8w z&bSErwp+37 zNJJ8?a|{r5Q3R0Z5s-LB1WHOwYC@7pCHWND#cL1cZ?{kJ368_*(UDWUDyb<}0y@o# zfMF016iMWPCb6obAxT$JlB6(2DrlXDTB&!0`!m??4F(qWMhjVZo?JXQmz`1*58Z=& zcDmB|S-E@j?BoFGix0flckqdS4jsPNzhfWyWIM98GxcLs89C(~dw%$_t;JjX-SD}E zfiGV;{8Q%8r}w9x>EEigW81>`kvnU@pK)4+xk9@+bNj9L!AAZ@SZ@q|)&BmY3+HZx zul~BeG4|}-;L%cHViQGQX?^zFfO0&#cHwel=d`lH9sJ-@Sl@n*(8J2>%Ac`IxyY?Q z{=GhWvC#gu-~Ia7*n{=+;qM?Ul_wy1+u7ho;=`>EwP^g~R@{unBds`!#@}tluZQpS zm)M~nYEifJWJGx?_6DcTy>#uh%>!H9=hb^(v`=m3F1{L>db=<5_tm+_&knAQ2EU$s Mu9UqpbNZeC0BbUo^Z)<= literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/StoreLogo.png b/windows/RNFS.Tests/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;iX1yMDiS)sh0wKi!36 zL!Wmq?P^Ku&rK~HJd97KkLTRl>ScGFYZNlYytWnhmuu|)L&ND8_PmkayQb{HOY640 bno1(wj@u8DCVuFR|31B*4ek@pZJqxCDDe1x literal 0 HcmV?d00001 diff --git a/windows/RNFS.Tests/Assets/Wide310x150Logo.scale-200.png b/windows/RNFS.Tests/Assets/Wide310x150Logo.scale-200.png new file mode 100644 index 0000000000000000000000000000000000000000..288995b397fdbef1fb7e85afd71445d5de1952c5 GIT binary patch literal 3204 zcmbVPeQXow8NYmBd90>}0NP?GhXW~VaeThm=a0tV#EwJMI!)6M3}|c4_Bl3=Kd>G0 z(GHx1wl<7(tP?FsOQkTilSo*iIvF%uArExJ73~P zSv1xEy!U(Wd4A9D`FQV@W3@F^qJ@PEF$@z`Z!*BbFsS(^?B zyiAzJ+q})bkgiQHWqEb*jJD-coHYr1^iocg)l!Qa{Xqs-l~6J}p-|##ZHYofskQ3$ zI0;xzXyhazBeXhIsg5A=%ufo@f)1yy&ScKS0;HF^!r_2UE^lpZEom(+@duma3awTv zCrCL-%D_SvYWIcdHkmI}#50(fkUi)Qgx!80ju>g1za^}ff>JI8Z@^-iCiaCgg@TgF z+vtE?Q9{VQUX&MW9SYYmGcxA14%N2@7FwBTD4N<(2{nWgV8$e3?-F=L^&FrtWn~(U_Q~~^uYiyeY6-KoTnfh9AWz@ zIKje0)u!_Lw)E}G!#kEfwKVdNt(UAf9*f>tEL_(=xco-T%jTi@7YlC3hs2ik%Le0H ztj}RTeCF(5mwvi3_56>-yB?l;J>-1%!9~=fs|QcNG3J~a@JCu`4SB460s0ZO+##4fFUSGLcj_ja^fL4&BKALfb#$6$O?>P@qx2Agl^x0i&ugt zsy5Pyu=()`7HRMG3IB7F1@`_ z+-!J%#i6e^U$e#+C%Q>_qVRzWRsG^W_n+@OcX@vzI&z;mzHNb!GQ?LWA(wtpqHqTM z1OFw_{Zn?fD)p)`c`kOgv{de=v@suGRqY{N^U7gI1VF3*F=obwaXI6ob5__Yn zVTguS!%(NI09J8x#AO_aW!9W7k*UvB;IWDFC3srwftr{kHj%g)fvnAm;&h_dnl~

MY- zf+K}sCe8qU6Ujs`3ua{U0Of$R_gVQBuUA za0v=mu#vIOqiiAZOr&h*$WyOw&k-xr$;G4Ixa!#TJNr>95(h>l%)PUy4p+^SgR(uR zta%k*?ny-+nAr8spEk1fo{J4i!b^Fia`N{_F6@zidA2ZTTrjl#^5Z-2KfB@Cu}l9s z(*|Z2jc?p~vn2f)3y9i*7zJV1L{$?|&q)4oaT;uXi6>1GkRXVTOzAz(RHEmr=eFIi z`}<>-Q?K0GN8!IYxeP1XKXO+jsJbp~o^);Bc;%b7Flpe7;1`Ny@3r7ZR;?R)aJt8C ziNlEC<@3f_lIV4TwV}&e;D!Ee5_|e#g0LUh=5vmYWYm7&2h*M>QPKvGh9-)wfMMW3 z8J9b%1k7dzPzO0_NGQy92BZ^FR6R~6;^6?lqO;-QUP4BY%cG%3vEhbm#>4vIhPBh3 z-+pZGjh$x%Hp{?=FHsMp0&wNPlj00us{&`1ZOZTqs8%4X&xH=UDr*xyBW(Zp&Em94 zf)ZSfn#yg0N)>!1kWdkqJ^S*z0FF5|fj&qcE#Na|%OY0$uO>!&hP+1ywfD_WXk@4J(?MBftK7>$Nvqh@tDuarN%PrTLQ2Uzysx>UV=V zk^RrDSvdQ?0;=hY67EgII-f4`t=+i*yS=Y~!XlqIy_4x&%+OdfbKOFPXS2X5%4R{N z$SQMX^AK6(fA + + + + + + + + RNFS.Tests + ericroz + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/windows/RNFS.Tests/Properties/AssemblyInfo.cs b/windows/RNFS.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..3c08d419 --- /dev/null +++ b/windows/RNFS.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("RNFS.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RNFS.Tests")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: AssemblyMetadata("TargetPlatform","UAP")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: ComVisible(false)] \ No newline at end of file diff --git a/windows/RNFS.Tests/Properties/UnitTestApp.rd.xml b/windows/RNFS.Tests/Properties/UnitTestApp.rd.xml new file mode 100644 index 00000000..efee59d2 --- /dev/null +++ b/windows/RNFS.Tests/Properties/UnitTestApp.rd.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/windows/RNFS.Tests/RNFS.Tests.csproj b/windows/RNFS.Tests/RNFS.Tests.csproj new file mode 100644 index 00000000..149564e1 --- /dev/null +++ b/windows/RNFS.Tests/RNFS.Tests.csproj @@ -0,0 +1,151 @@ + + + + + Debug + x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6} + AppContainerExe + Properties + RNFS.Tests + RNFS.Tests + en-US + UAP + 10.0.14393.0 + 10.0.10586.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + RNFS.Tests_TemporaryKey.pfx + $(VisualStudioVersion) + + + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x86 + false + prompt + true + + + bin\x86\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x86 + false + prompt + true + true + + + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + ARM + false + prompt + true + + + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + ARM + false + prompt + true + true + + + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x64 + false + prompt + true + + + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x64 + false + prompt + true + true + + + + + + + + + + + + UnitTestApp.xaml + + + + + + MSBuild:Compile + Designer + + + + + Designer + + + + + + + + + + + + + + + + {c7673ad5-e3aa-468c-a5fd-fa38154e205c} + ReactNative + + + {746610d0-8693-11e7-a20d-bf83f7366778} + RNFS + + + + + + + 14.0 + + + + \ No newline at end of file diff --git a/windows/RNFS.Tests/RNFS.Tests.nuget.props b/windows/RNFS.Tests/RNFS.Tests.nuget.props new file mode 100644 index 00000000..f59c6d8a --- /dev/null +++ b/windows/RNFS.Tests/RNFS.Tests.nuget.props @@ -0,0 +1,18 @@ + + + + True + NuGet + C:\src\react-native-fs\windows\RNFS.Tests\project.lock.json + $(UserProfile)\.nuget\packages\ + C:\Users\ericroz\.nuget\packages\ + ProjectJson + 4.3.0 + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + + + \ No newline at end of file diff --git a/windows/RNFS.Tests/RNFS.Tests.nuget.targets b/windows/RNFS.Tests/RNFS.Tests.nuget.targets new file mode 100644 index 00000000..781fadb9 --- /dev/null +++ b/windows/RNFS.Tests/RNFS.Tests.nuget.targets @@ -0,0 +1,9 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + + + \ No newline at end of file diff --git a/windows/RNFS.Tests/RNFS.Tests_TemporaryKey.pfx b/windows/RNFS.Tests/RNFS.Tests_TemporaryKey.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ffcd21ee7379ddae2577989af34def75257a4aca GIT binary patch literal 2512 zcmZXUc|6qX7stOd#xfC+okF7-yTN6IEQKc7Cf%seSW}i^?4p>MvAgz3V$u+Cagj@r zsD`m5Bx@POG>95Y_U?3Fzu&#D-|P1}uk)O9-k;|@&-2f7kOXKi7{rAnKofb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--git a/windows/RNFS.Tests/RNFSManagerTests.cs b/windows/RNFS.Tests/RNFSManagerTests.cs new file mode 100644 index 00000000..137e48d7 --- /dev/null +++ b/windows/RNFS.Tests/RNFSManagerTests.cs @@ -0,0 +1,1632 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json.Linq; +using ReactNative.Bridge; +using ReactNative.Modules.Core; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Windows.Storage; + +namespace RNFS.Tests +{ + [TestClass] + public class RNFSManagerTests + { + [TestMethod] + public void RNFSManager_Constants() + { + var context = new ReactContext(); + var manager = new RNFSManager(context); + var constants = manager.Constants; + + Assert.IsTrue(constants.Keys.Contains("RNFSCachesDirectoryPath")); + Assert.IsTrue(constants.Keys.Contains("RNFSRoamingDirectoryPath")); + Assert.IsTrue(constants.Keys.Contains("RNFSDocumentDirectoryPath")); + Assert.IsTrue(constants.Keys.Contains("RNFSTemporaryDirectoryPath")); + Assert.IsTrue(constants.Keys.Contains("RNFSFileTypeRegular")); + Assert.IsTrue(constants.Keys.Contains("RNFSFileTypeDirectory")); + Assert.AreNotEqual(constants["RNFSFileTypeRegular"], constants["RNFSFileTypeDirectory"]); + } + + [TestMethod] + public async Task RNFSManager_writeFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + var base64Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(hello)); + var promise = new MockPromise(); + manager.writeFile(path, base64Content, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual(hello, contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_writeFile_ExistingFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello Hello Earth"); + + // Run test + var hello = "Hello World"; + var base64Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(hello)); + var promise = new MockPromise(); + manager.writeFile(path, base64Content, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual("Hello World Earth", contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_writeFile_ExistingDirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var hello = "Hello World"; + var base64Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(hello)); + var promise = new MockPromise(); + manager.writeFile(path, base64Content, promise); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_writeFile_Fail() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var promise = new MockPromise(); + manager.writeFile("badPath", "", promise); + + await AssertRejectAsync( + promise, + ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + } + + [TestMethod] + public async Task RNFSManager_write() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + var bytes = Encoding.UTF8.GetBytes(hello); + var base64Content = Convert.ToBase64String(bytes); + var promise = new MockPromise(); + manager.write(path, base64Content, 0, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual(hello, contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_NegativeSeek_Ignored() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + var bytes = Encoding.UTF8.GetBytes(hello); + var base64Content = Convert.ToBase64String(bytes); + var promise = new MockPromise(); + manager.write(path, base64Content, -1, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual(hello, contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_ExistingFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var bytes = Encoding.UTF8.GetBytes(hello); + var base64Content = Convert.ToBase64String(bytes); + var promise = new MockPromise(); + manager.write(path, base64Content, bytes.Length, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual(hello + hello, contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_ExistingDirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var hello = "Hello World"; + var base64Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(hello)); + var promise = new MockPromise(); + manager.write(path, base64Content, 0, promise); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_NewFile_Seek() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + var bytes = Encoding.UTF8.GetBytes(hello); + var base64Content = Convert.ToBase64String(bytes); + var promise = new MockPromise(); + manager.write(path, base64Content, 4, promise); + await promise.Task; + + // Assert + var actualBytes = File.ReadAllBytes(path); + Assert.IsTrue(actualBytes.Skip(4).SequenceEqual(bytes)); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_Overwrite() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var earth = "Earth"; + var bytes = Encoding.UTF8.GetBytes(earth); + var base64Content = Convert.ToBase64String(bytes); + var promise = new MockPromise(); + manager.write(path, base64Content, 6, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(path); + Assert.AreEqual("Hello Earth", contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_write_Fail() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var promise = new MockPromise(); + manager.write("badPath", "", 0, promise); + await AssertRejectAsync( + promise, + ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + } + + [TestMethod] + public async Task RNFSManager_exists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test (true) + var promise = new MockPromise(); + manager.exists(path, promise); + var exists = await promise.Task; + Assert.IsTrue(exists is bool); + Assert.IsTrue((bool)exists); + + // Run test (false) + var fakePath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + promise = new MockPromise(); + manager.exists(fakePath, promise); + exists = await promise.Task; + Assert.IsTrue(exists is bool); + Assert.IsFalse((bool)exists); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_exists_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test (true) + var promise = new MockPromise(); + manager.exists(path, promise); + var exists = await promise.Task; + Assert.IsTrue(exists is bool); + Assert.IsTrue((bool)exists); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_exists_InvalidPath() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test (false) + var promise = new MockPromise(); + manager.exists(string.Concat(Path.GetInvalidPathChars()), promise); + var exists = await promise.Task; + Assert.IsTrue(exists is bool); + Assert.IsFalse((bool)exists); + } + + [TestMethod] + public async Task RNFSManager_readFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var promise = new MockPromise(); + manager.readFile(path, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + var base64Content = (string)result; + var contents = Encoding.UTF8.GetString(Convert.FromBase64String(base64Content)); + Assert.AreEqual(hello, contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_readFile_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.readFile(path, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_readFile_InvalidPath() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.readFile("badPath", promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_readFile_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var promise = new MockPromise(); + manager.readFile(path, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_read() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test (part 1) + var promise = new MockPromise(); + manager.read(path, 5, 0, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + var base64Content = (string)result; + var contents = Encoding.UTF8.GetString(Convert.FromBase64String(base64Content)); + Assert.AreEqual("Hello", contents); + + // Run test (part 2) + promise = new MockPromise(); + manager.read(path, 5, 6, promise); + result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + base64Content = (string)result; + contents = Encoding.UTF8.GetString(Convert.FromBase64String(base64Content)); + Assert.AreEqual("World", contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_read_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.read(path, 0, 0, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_read_InvalidPath() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.read("badPath", 0, 0, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_read_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var promise = new MockPromise(); + manager.read(path, 10, 0, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_read_MoreThanContent() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var promise = new MockPromise(); + manager.read(path, 100, 0, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + var base64Content = (string)result; + var contents = Encoding.UTF8.GetString(Convert.FromBase64String(base64Content)); + Assert.AreEqual( + hello + string.Join("", Enumerable.Repeat('\0', 100 - hello.Length)), + contents); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_hash() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var promise = new MockPromise(); + manager.hash(path, "sha256", promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + var hash = (string)result; + using (var algorithm = SHA256.Create()) + { + algorithm.Initialize(); + var expectedHash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(hello)); + var expectedHashString = string.Join("", expectedHash.Select(b => string.Format("{0:x2}", b))); + Assert.AreEqual(expectedHashString, hash); + } + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_hash_InvalidAlgorithm() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.hash(path, "foo", promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("Invalid hash algorithm.", ex.Message)); + } + + [TestMethod] + public async Task RNFSManager_hash_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.hash(path, "sha256", promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManger_hash_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var promise = new MockPromise(); + manager.hash(path, "sha256", promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_moveFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var newPath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.moveFile(path, newPath, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(newPath); + Assert.AreEqual(hello, contents); + Assert.IsFalse(new FileInfo(path).Exists); + + // Cleanup + File.Delete(newPath); + } + + [TestMethod] + public async Task RNFSManager_moveFile_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var newPath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.moveFile(path, newPath, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_copyFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var newPath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.copyFile(path, newPath, promise); + await promise.Task; + + // Assert + var contents = File.ReadAllText(newPath); + Assert.AreEqual(hello, contents); + Assert.IsTrue(new FileInfo(path).Exists); + + // Cleanup + File.Delete(path); + File.Delete(newPath); + } + + [TestMethod] + public async Task RNFSManager_copyFile_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var newPath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.copyFile(path, newPath, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("ENOENT", ex.Code)); + } + + [TestMethod] + public async Task RNFSManager_readDir() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var path = Path.Combine(dirpath, Guid.NewGuid().ToString()); + Directory.CreateDirectory(dirpath); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var promise = new MockPromise(); + manager.readDir(dirpath, promise); + var result = await promise.Task; + var fileInfos = (JArray)result; + Assert.AreEqual(1, fileInfos.Count); + var item = fileInfos[0]; + var fileInfo = (JObject)item; + Assert.AreEqual(0, fileInfo.Value("type")); + Assert.AreEqual(11, fileInfo.Value("size")); + Assert.AreEqual(path, fileInfo.Value("path")); + Assert.AreEqual(Path.GetFileName(path), fileInfo.Value("name")); + Assert.AreEqual( + ConvertToUnixTimestamp(new FileInfo(path).LastWriteTimeUtc), + fileInfo.Value("mtime")); + + // Cleanup + File.Delete(path); + Directory.Delete(dirpath); + } + + [TestMethod] + public async Task RNFSManager_readDir_Empty() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(dirpath); + + // Run test + var promise = new MockPromise(); + manager.readDir(dirpath, promise); + var result = await promise.Task; + var fileInfos = (JArray)result; + Assert.AreEqual(0, fileInfos.Count); + + // Cleanup + Directory.Delete(dirpath); + } + + [TestMethod] + public async Task RNFSManager_readDir_Multiple() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var path1 = Path.Combine(dirpath, Guid.NewGuid().ToString()); + var path2 = Path.Combine(dirpath, Guid.NewGuid().ToString()); + Directory.CreateDirectory(dirpath); + var hello = "Hello World"; + File.WriteAllText(path1, hello); + File.WriteAllText(path2, hello); + + // Run test + var promise = new MockPromise(); + manager.readDir(dirpath, promise); + var result = await promise.Task; + var fileInfos = (JArray)result; + Assert.AreEqual(2, fileInfos.Count); + + // Cleanup + File.Delete(path1); + File.Delete(path2); + Directory.Delete(dirpath); + } + + [TestMethod] + public async Task RNFSManager_readDir_Subdirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var subdirpath = Path.Combine(dirpath, Guid.NewGuid().ToString()); + Directory.CreateDirectory(dirpath); + Directory.CreateDirectory(subdirpath); + + // Run test + var promise = new MockPromise(); + manager.readDir(dirpath, promise); + var result = await promise.Task; + var fileInfos = (JArray)result; + Assert.AreEqual(1, fileInfos.Count); + var item = fileInfos[0]; + var fileInfo = (IDictionary)item; + Assert.IsTrue(fileInfo.ContainsKey("type")); + Assert.AreEqual(1, fileInfo["type"].Value()); + Assert.AreEqual(0, fileInfo["size"].Value()); + Assert.AreEqual(subdirpath, fileInfo["path"].Value()); + Assert.AreEqual(subdirpath.Split(Path.DirectorySeparatorChar).Last(), fileInfo["name"].Value()); + Assert.AreEqual( + ConvertToUnixTimestamp(new DirectoryInfo(subdirpath).LastWriteTimeUtc), + fileInfo["mtime"].Value()); + + // Cleanup + Directory.Delete(subdirpath); + Directory.Delete(dirpath); + } + + [TestMethod] + public async Task RNFSManager_stat() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test + var promise = new MockPromise(); + manager.stat(path, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(JObject)); + var stat = (JObject)result; + Assert.AreEqual(0, stat.Value("type")); + Assert.AreEqual(11, stat.Value("size")); + Assert.AreEqual( + ConvertToUnixTimestamp(new FileInfo(path).CreationTimeUtc), + stat.Value("ctime")); + Assert.AreEqual( + ConvertToUnixTimestamp(new FileInfo(path).LastWriteTimeUtc), + stat.Value("mtime")); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_stat_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.stat(path, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("File does not exist.", ex.Message)); + } + + [TestMethod] + public async Task RNFSManager_stat_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var promise = new MockPromise(); + manager.stat(path, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(JObject)); + var stat = (JObject)result; + Assert.AreEqual(1, stat.Value("type")); + Assert.AreEqual(0, stat.Value("size")); + Assert.AreEqual( + ConvertToUnixTimestamp(new DirectoryInfo(path).CreationTimeUtc), + stat.Value("ctime")); + Assert.AreEqual( + ConvertToUnixTimestamp(new DirectoryInfo(path).LastWriteTimeUtc), + stat.Value("mtime")); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_unlink_Directory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var path1 = Path.Combine(dirpath, Guid.NewGuid().ToString()); + var path2 = Path.Combine(dirpath, Guid.NewGuid().ToString()); + Directory.CreateDirectory(dirpath); + var hello = "Hello World"; + File.WriteAllText(path1, hello); + File.WriteAllText(path2, hello); + + // Run test + var promise = new MockPromise(); + manager.unlink(dirpath, promise); + await promise.Task; + Assert.IsFalse(new DirectoryInfo(dirpath).Exists); + } + + [TestMethod] + public async Task RNFSManager_unlink_File() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test + var promise = new MockPromise(); + manager.unlink(path, promise); + await promise.Task; + Assert.IsFalse(new FileInfo(path).Exists); + } + + [TestMethod] + public async Task RNFSManager_unlink_Recursive() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var dirpath = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var subdirpath = Path.Combine(dirpath, Guid.NewGuid().ToString()); + var path = Path.Combine(dirpath, Guid.NewGuid().ToString()); + Directory.CreateDirectory(subdirpath); + var hello = "Hello World"; + File.WriteAllText(path, hello); + + // Run test + var promise = new MockPromise(); + manager.unlink(dirpath, promise); + await promise.Task; + Assert.IsFalse(new FileInfo(path).Exists); + Assert.IsFalse(new DirectoryInfo(subdirpath).Exists); + Assert.IsFalse(new DirectoryInfo(dirpath).Exists); + } + + [TestMethod] + public async Task RNFSManager_unlink_NotExists() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.unlink(path, promise); + await AssertRejectAsync(promise, ex => Assert.AreEqual("File does not exist.", ex.Message)); + } + + [TestMethod] + public async Task RNFSManager_mkdir() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.mkdir(path, null, promise); + await promise.Task; + + // Assert + Assert.IsTrue(new DirectoryInfo(path).Exists); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_mkdir_Intermediate() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var subdirpath = Path.Combine(path, Guid.NewGuid().ToString()); + var promise = new MockPromise(); + manager.mkdir(subdirpath, null, promise); + await promise.Task; + + // Assert + Assert.IsTrue(new DirectoryInfo(subdirpath).Exists); + Assert.IsTrue(new DirectoryInfo(path).Exists); + + // Cleanup + Directory.Delete(subdirpath); + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_mkdir_ExistingFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test + var promise = new MockPromise(); + manager.mkdir(path, null, promise); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is IOException)); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_mkdir_ExistingDirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var promise = new MockPromise(); + manager.mkdir(path, null, promise); + await promise.Task; + + // Assert + Assert.IsTrue(new DirectoryInfo(path).Exists); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_mkdir_Fail() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var promise = new MockPromise(); + manager.mkdir("badPath", null, promise); + + await AssertRejectAsync( + promise, + ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + } + + [TestMethod] + public async Task RNFSManager_getFSInfo() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var promise = new MockPromise(); + manager.getFSInfo(promise); + var result = await promise.Task; + var dictionary = result as IDictionary; + Assert.IsNotNull(dictionary); + Assert.IsTrue(dictionary.ContainsKey("freeSpace")); + Assert.IsTrue(dictionary.ContainsKey("totalSpace")); + } + + [TestMethod] + public async Task RNFSManager_touch() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var ctime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddDays(-1))); + var mtime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddHours(-1))); + var promise = new MockPromise(); + manager.touch( + path, + ConvertToUnixTimestamp(mtime), + ConvertToUnixTimestamp(ctime), + promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + Assert.AreEqual(path, (string)result); + var fileInfo = new FileInfo(path); + Assert.IsTrue(fileInfo.Exists); + Assert.AreEqual(ctime, fileInfo.CreationTime); + Assert.AreEqual(mtime, fileInfo.LastWriteTime); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_touch_ExistingFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test + var ctime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddDays(-1))); + var mtime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddHours(-1))); + var promise = new MockPromise(); + manager.touch( + path, + ConvertToUnixTimestamp(mtime), + ConvertToUnixTimestamp(ctime), + promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(string)); + Assert.AreEqual(path, (string)result); + var fileInfo = new FileInfo(path); + Assert.IsTrue(fileInfo.Exists); + Assert.AreEqual(ctime, fileInfo.CreationTime); + Assert.AreEqual(mtime, fileInfo.LastWriteTime); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + public async Task RNFSManager_touch_ExistingDirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var ctime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddDays(-1))); + var mtime = ConvertFromUnixTimestamp(ConvertToUnixTimestamp(DateTime.Now.AddHours(-1))); + var promise = new MockPromise(); + manager.touch( + path, + ConvertToUnixTimestamp(mtime), + ConvertToUnixTimestamp(ctime), + promise); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/get" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(JObject)); + var json = (JObject)result; + Assert.AreEqual(1, json["jobId"].Value()); + Assert.AreEqual(new FileInfo(path).Length, json["bytesWritten"].Value()); + Assert.AreEqual(200, json["statusCode"].Value()); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile_Progress() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context); + var waitHandle = new AutoResetEvent(false); + var progressCount = 0; + manager.Emitter = CreateEventEmitter((name, data) => + { + if (name == "DownloadProgress-1") + { + progressCount++; + } + }); + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/bytes/102400" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 10 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + await promise.Task; + Assert.IsTrue(progressCount >= 10); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile_Headers() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Run test + var expectedHeaders = new JObject + { + { "Accept", "foo/bar" }, + { "ContentLength", 0 }, + { "X-Custom-Header", "qux" } + }; + + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/headers" }, + { "jobId", 1 }, + { "headers", expectedHeaders }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + await promise.Task; + var actualHeaders = (JObject)JObject.Parse(File.ReadAllText(path))["headers"]; + Assert.AreEqual(0, actualHeaders.Value("ContentLength")); + Assert.AreEqual("qux", actualHeaders.Value("X-Custom-Header")); + Assert.AreEqual("foo/bar", actualHeaders.Value("Accept")); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile_ExistingFile() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + File.WriteAllText(path, "Hello World"); + + // Run test + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/get" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(JObject)); + var json = (JObject)result; + Assert.AreEqual(1, json["jobId"].Value()); + Assert.AreEqual(new FileInfo(path).Length, json["bytesWritten"].Value()); + Assert.AreEqual(200, json["statusCode"].Value()); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile_ExistingDirectory() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Setup environment + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + + // Run test + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/get" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is UnauthorizedAccessException)); + + // Cleanup + Directory.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_downloadFile_Redirect() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/redirect/1" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + var result = await promise.Task; + Assert.IsInstanceOfType(result, typeof(JObject)); + var json = (JObject)result; + Assert.AreEqual(1, json["jobId"].Value()); + Assert.AreEqual(new FileInfo(path).Length, json["bytesWritten"].Value()); + Assert.AreEqual(200, json["statusCode"].Value()); + + // Cleanup + File.Delete(path); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_stopDownload() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/delay/10" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + manager.stopDownload(1); + await AssertRejectAsync(promise, ex => Assert.IsTrue(ex.InnerException is TaskCanceledException)); + Assert.IsFalse(new FileInfo(path).Exists); + } + + [TestMethod] + [TestCategory("Network")] + public async Task RNFSManager_stopDownload_AfterComplete() + { + // Initialize module + var context = new ReactContext(); + var manager = new RNFSManager(context) + { + Emitter = CreateEventEmitter((_, __) => { }), + }; + + // Run test + var tempFolder = ApplicationData.Current.TemporaryFolder.Path; + var path = Path.Combine(tempFolder, Guid.NewGuid().ToString()); + var options = new JObject + { + { "toFile", path }, + { "fromUrl", "http://httpbin.org/delay/1" }, + { "jobId", 1 }, + { "headers", new JObject() }, + { "progressDivider", 100 }, + }; + + var promise = new MockPromise(); + manager.downloadFile(options, promise); + await promise.Task; + manager.stopDownload(1); + Assert.IsTrue(new FileInfo(path).Exists); + + // Cleanup + File.Delete(path); + } + + private static async Task AssertRejectAsync(MockPromise promise, Action assert) + { + try + { + await promise.Task; + } + catch (RejectException ex) + { + assert(ex); + return; + } + + Assert.Fail("No exception thrown."); + } + + public static double ConvertToUnixTimestamp(DateTime date) + { + var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var diff = date.ToUniversalTime() - origin; + return Math.Floor(diff.TotalSeconds); + } + + public static DateTime ConvertFromUnixTimestamp(double timestamp) + { + var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var diff = TimeSpan.FromSeconds(timestamp); + var dateTimeUtc = origin + diff; + return dateTimeUtc.ToLocalTime(); + } + + public static RCTNativeAppEventEmitter CreateEventEmitter(Action onEmit) + { + return new RCTNativeAppEventEmitter + { + InvocationHandler = new MockInvocationHandler((name, args) => + { + if (name == "emit") + { + var eventName = (string)args[0]; + var eventData = args[1]; + onEmit(eventName, eventData); + return; + } + + throw new NotSupportedException(); + }), + }; + } + + class MockPromise : IPromise + { + private readonly TaskCompletionSource _tcs = new TaskCompletionSource(); + public Task Task + { + get + { + return _tcs.Task; + } + } + + public void Reject(string code, string message) + { + _tcs.SetException(new RejectException(code, message)); + } + + public void Reject(string code, Exception exception) + { + _tcs.SetException(new RejectException(code, null, exception)); + } + + public void Reject(string code, string message, Exception exception) + { + _tcs.SetException(new RejectException(code, message, exception)); + } + + public void Reject(string message) + { + _tcs.SetException(new RejectException(null, message)); + } + + public void Reject(Exception exception) + { + _tcs.SetException(new RejectException(null, null, exception)); + } + + public void Resolve(object value) + { + _tcs.SetResult(value); + } + } + + class RejectException : Exception + { + public RejectException(string code, string message, Exception innerException) + : base(message, innerException) + { + Code = code; + } + + public RejectException(string code, string message) + : base(message) + { + Code = code; + } + + public string Code { get; } + } + + class MockInvocationHandler : IInvocationHandler + { + private readonly Action _onInvoke; + public MockInvocationHandler(Action onInvoke) + { + _onInvoke = onInvoke; + } + + public void Invoke(string name, object[] args) + { + _onInvoke(name, args); + } + } + } +} \ No newline at end of file diff --git a/windows/RNFS.Tests/UnitTestApp.xaml b/windows/RNFS.Tests/UnitTestApp.xaml new file mode 100644 index 00000000..42d19db9 --- /dev/null +++ b/windows/RNFS.Tests/UnitTestApp.xaml @@ -0,0 +1,8 @@ + + + diff --git a/windows/RNFS.Tests/UnitTestApp.xaml.cs b/windows/RNFS.Tests/UnitTestApp.xaml.cs new file mode 100644 index 00000000..8b60d67d --- /dev/null +++ b/windows/RNFS.Tests/UnitTestApp.xaml.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using Windows.ApplicationModel; +using Windows.ApplicationModel.Activation; +using Windows.Foundation; +using Windows.Foundation.Collections; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Controls.Primitives; +using Windows.UI.Xaml.Data; +using Windows.UI.Xaml.Input; +using Windows.UI.Xaml.Media; +using Windows.UI.Xaml.Navigation; + +namespace RNFS.Tests +{ + /// + /// Provides application-specific behavior to supplement the default Application class. + /// + sealed partial class App : Application + { + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// + public App() + { + this.InitializeComponent(); + this.Suspending += OnSuspending; + } + + /// + /// Invoked when the application is launched normally by the end user. Other entry points + /// will be used such as when the application is launched to open a specific file. + /// + /// Details about the launch request and process. + protected override void OnLaunched(LaunchActivatedEventArgs e) + { + +#if DEBUG + if (System.Diagnostics.Debugger.IsAttached) + { + this.DebugSettings.EnableFrameRateCounter = true; + } +#endif + + Frame rootFrame = Window.Current.Content as Frame; + + // Do not repeat app initialization when the Window already has content, + // just ensure that the window is active + if (rootFrame == null) + { + // Create a Frame to act as the navigation context and navigate to the first page + rootFrame = new Frame(); + + rootFrame.NavigationFailed += OnNavigationFailed; + + if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) + { + //TODO: Load state from previously suspended application + } + + // Place the frame in the current Window + Window.Current.Content = rootFrame; + } + + Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI(); + + // Ensure the current window is active + Window.Current.Activate(); + + Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments); + } + + /// + /// Invoked when Navigation to a certain page fails + /// + /// The Frame which failed navigation + /// Details about the navigation failure + void OnNavigationFailed(object sender, NavigationFailedEventArgs e) + { + throw new Exception("Failed to load Page " + e.SourcePageType.FullName); + } + + /// + /// Invoked when application execution is being suspended. Application state is saved + /// without knowing whether the application will be terminated or resumed with the contents + /// of memory still intact. + /// + /// The source of the suspend request. + /// Details about the suspend request. + private void OnSuspending(object sender, SuspendingEventArgs e) + { + var deferral = e.SuspendingOperation.GetDeferral(); + //TODO: Save application state and stop any background activity + deferral.Complete(); + } + } +} diff --git a/windows/RNFS.Tests/project.json b/windows/RNFS.Tests/project.json new file mode 100644 index 00000000..32a707e6 --- /dev/null +++ b/windows/RNFS.Tests/project.json @@ -0,0 +1,18 @@ +{ + "dependencies": { + "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.3", + "MSTest.TestAdapter": "1.1.18", + "MSTest.TestFramework": "1.1.18" + }, + "frameworks": { + "uap10.0.10586": {} + }, + "runtimes": { + "win10-arm": {}, + "win10-arm-aot": {}, + "win10-x86": {}, + "win10-x86-aot": {}, + "win10-x64": {}, + "win10-x64-aot": {} + } +} \ No newline at end of file diff --git a/windows/RNFS.sln b/windows/RNFS.sln new file mode 100644 index 00000000..627251fa --- /dev/null +++ b/windows/RNFS.sln @@ -0,0 +1,120 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.3 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RNFS", "RNFs\RNFS.csproj", "{746610D0-8693-11E7-A20D-BF83F7366778}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReactNative", "..\node_modules\react-native-windows\ReactWindows\ReactNative\ReactNative.csproj", "{C7673AD5-E3AA-468C-A5FD-FA38154E205C}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ReactNative.Shared", "..\node_modules\react-native-windows\ReactWindows\ReactNative.Shared\ReactNative.Shared.shproj", "{EEA8B852-4D07-48E1-8294-A21AB5909FE5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ChakraBridge", "..\node_modules\react-native-windows\ReactWindows\ChakraBridge\ChakraBridge.vcxproj", "{4B72C796-16D5-4E3A-81C0-3E36F531E578}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RNFS.Tests", "RNFS.Tests\RNFS.Tests.csproj", "{8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}" +EndProject +Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\node_modules\react-native-windows\ReactWindows\ReactNative.Shared\ReactNative.Shared.projitems*{c7673ad5-e3aa-468c-a5fd-fa38154e205c}*SharedItemsImports = 4 + ..\node_modules\react-native-windows\ReactWindows\ReactNative.Shared\ReactNative.Shared.projitems*{eea8b852-4d07-48e1-8294-a21ab5909fe5}*SharedItemsImports = 13 + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Development|ARM = Development|ARM + Development|x64 = Development|x64 + Development|x86 = Development|x86 + Release|ARM = Release|ARM + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|ARM.ActiveCfg = Debug|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|ARM.Build.0 = Debug|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|x64.ActiveCfg = Debug|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|x64.Build.0 = Debug|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|x86.ActiveCfg = Debug|x86 + {746610D0-8693-11E7-A20D-BF83F7366778}.Debug|x86.Build.0 = Debug|x86 + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|ARM.ActiveCfg = Development|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|ARM.Build.0 = Development|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|x64.ActiveCfg = Development|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|x64.Build.0 = Development|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|x86.ActiveCfg = Development|x86 + {746610D0-8693-11E7-A20D-BF83F7366778}.Development|x86.Build.0 = Development|x86 + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|ARM.ActiveCfg = Release|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|ARM.Build.0 = Release|ARM + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|x64.ActiveCfg = Release|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|x64.Build.0 = Release|x64 + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|x86.ActiveCfg = Release|x86 + {746610D0-8693-11E7-A20D-BF83F7366778}.Release|x86.Build.0 = Release|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|ARM.ActiveCfg = Debug|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|ARM.Build.0 = Debug|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|x64.ActiveCfg = Debug|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|x64.Build.0 = Debug|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|x86.ActiveCfg = Debug|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Debug|x86.Build.0 = Debug|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|ARM.ActiveCfg = Debug|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|ARM.Build.0 = Debug|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|x64.ActiveCfg = Debug|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|x64.Build.0 = Debug|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|x86.ActiveCfg = Debug|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Development|x86.Build.0 = Debug|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|ARM.ActiveCfg = Release|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|ARM.Build.0 = Release|ARM + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|x64.ActiveCfg = Release|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|x64.Build.0 = Release|x64 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|x86.ActiveCfg = Release|x86 + {C7673AD5-E3AA-468C-A5FD-FA38154E205C}.Release|x86.Build.0 = Release|x86 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|ARM.ActiveCfg = Debug|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|ARM.Build.0 = Debug|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|x64.ActiveCfg = Debug|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|x64.Build.0 = Debug|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|x86.ActiveCfg = Debug|Win32 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Debug|x86.Build.0 = Debug|Win32 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|ARM.ActiveCfg = Debug|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|ARM.Build.0 = Debug|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|x64.ActiveCfg = Debug|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|x64.Build.0 = Debug|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|x86.ActiveCfg = Debug|Win32 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Development|x86.Build.0 = Debug|Win32 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|ARM.ActiveCfg = Release|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|ARM.Build.0 = Release|ARM + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|x64.ActiveCfg = Release|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|x64.Build.0 = Release|x64 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|x86.ActiveCfg = Release|Win32 + {4B72C796-16D5-4E3A-81C0-3E36F531E578}.Release|x86.Build.0 = Release|Win32 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|ARM.ActiveCfg = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|ARM.Build.0 = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|ARM.Deploy.0 = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x64.ActiveCfg = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x64.Build.0 = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x64.Deploy.0 = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x86.ActiveCfg = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x86.Build.0 = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Debug|x86.Deploy.0 = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|ARM.ActiveCfg = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|ARM.Build.0 = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|ARM.Deploy.0 = Debug|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x64.ActiveCfg = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x64.Build.0 = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x64.Deploy.0 = Debug|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x86.ActiveCfg = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x86.Build.0 = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Development|x86.Deploy.0 = Debug|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|ARM.ActiveCfg = Release|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|ARM.Build.0 = Release|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|ARM.Deploy.0 = Release|ARM + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x64.ActiveCfg = Release|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x64.Build.0 = Release|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x64.Deploy.0 = Release|x64 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x86.ActiveCfg = Release|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x86.Build.0 = Release|x86 + {8D2229AC-F6EC-4FBD-9AAC-FE4792DA98C6}.Release|x86.Deploy.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FBB6610F-6707-4A34-9D3B-3E0709F7822A} + EndGlobalSection +EndGlobal diff --git a/windows/RNFS/Properties/AssemblyInfo.cs b/windows/RNFS/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..3efc649d --- /dev/null +++ b/windows/RNFS/Properties/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("RNFS")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RNFS")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: ComVisible(false)] + +[assembly: InternalsVisibleTo("RNFS.Tests")] \ No newline at end of file diff --git a/windows/RNFS/Properties/RNFS.rd.xml b/windows/RNFS/Properties/RNFS.rd.xml new file mode 100644 index 00000000..039c5da3 --- /dev/null +++ b/windows/RNFS/Properties/RNFS.rd.xml @@ -0,0 +1,28 @@ + + + + + + + + + diff --git a/windows/RNFS/RNFS.csproj b/windows/RNFS/RNFS.csproj new file mode 100644 index 00000000..c314cf0c --- /dev/null +++ b/windows/RNFS/RNFS.csproj @@ -0,0 +1,153 @@ + + + + + Debug + x86 + {746610D0-8693-11E7-A20D-BF83F7366778} + Library + Properties + RNFS + RNFS + en-US + UAP + 10.0.10586.0 + 10.0.10240.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + ..\..\node_modules + + + ..\.. + + + x86 + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x86 + false + prompt + + + x86 + bin\x86\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x86 + false + prompt + + + ARM + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + ARM + false + prompt + + + ARM + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + ARM + false + prompt + + + x64 + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x64 + false + prompt + + + x64 + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x64 + false + prompt + + + true + bin\x86\Development\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + true + full + x86 + false + prompt + MinimumRecommendedRules.ruleset + + + true + bin\ARM\Development\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + true + full + ARM + false + prompt + MinimumRecommendedRules.ruleset + + + true + bin\x64\Development\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + true + full + x64 + false + prompt + MinimumRecommendedRules.ruleset + + + + + + + + + + + + + + {c7673ad5-e3aa-468c-a5fd-fa38154e205c} + ReactNative + + + + 14.0 + + + + \ No newline at end of file diff --git a/windows/RNFS/RNFSManager.cs b/windows/RNFS/RNFSManager.cs new file mode 100644 index 00000000..49ad1a85 --- /dev/null +++ b/windows/RNFS/RNFSManager.cs @@ -0,0 +1,645 @@ +using Newtonsoft.Json.Linq; +using ReactNative.Bridge; +using ReactNative.Modules.Core; +using ReactNative.Modules.Network; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Windows.ApplicationModel; +using Windows.Storage; + +namespace RNFS +{ + class RNFSManager : ReactContextNativeModuleBase + { + private const int FileType = 0; + private const int DirectoryType = 1; + + private static readonly IReadOnlyDictionary> s_hashAlgorithms = + new Dictionary> + { + { "md5", () => MD5.Create() }, + { "sha1", () => SHA1.Create() }, + { "sha256", () => SHA256.Create() }, + { "sha384", () => SHA384.Create() }, + { "sha512", () => SHA512.Create() }, + }; + + private readonly TaskCancellationManager _tasks = new TaskCancellationManager(); + private readonly HttpClient _httpClient = new HttpClient(); + + private RCTNativeAppEventEmitter _emitter; + + public RNFSManager(ReactContext reactContext) + : base(reactContext) + { + } + + public override string Name + { + get + { + return "RNFSManager"; + } + } + + internal RCTNativeAppEventEmitter Emitter + { + get + { + if (_emitter == null) + { + return Context.GetJavaScriptModule(); + } + + return _emitter; + } + set + { + _emitter = value; + } + } + + public override IReadOnlyDictionary Constants + { + get + { + var constants = new Dictionary + { + { "RNFSMainBundlePath", Package.Current.InstalledLocation.Path }, + { "RNFSCachesDirectoryPath", ApplicationData.Current.LocalCacheFolder.Path }, + { "RNFSRoamingDirectoryPath", ApplicationData.Current.RoamingFolder.Path }, + { "RNFSDocumentDirectoryPath", ApplicationData.Current.LocalFolder.Path }, + { "RNFSTemporaryDirectoryPath", ApplicationData.Current.TemporaryFolder.Path }, + { "RNFSFileTypeRegular", 0 }, + { "RNFSFileTypeDirectory", 1 }, + }; + + var external = GetFolderPathSafe(() => KnownFolders.RemovableDevices); + if (external != null) + { + var externalItems = KnownFolders.RemovableDevices.GetItemsAsync().AsTask().Result; + if (externalItems.Count > 0) + { + constants.Add("RNFSExternalDirectoryPath", externalItems[0].Path); + } + constants.Add("RNFSExternalDirectoryPaths", externalItems.Select(i => i.Path).ToArray()); + } + + var pictures = GetFolderPathSafe(() => KnownFolders.PicturesLibrary); + if (pictures != null) + { + constants.Add("RNFSPicturesDirectoryPath", pictures); + } + + return constants; + } + } + + [ReactMethod] + public async void writeFile(string filepath, string base64Content, IPromise promise) + { + try + { + // TODO: open file on background thread? + using (var file = File.OpenWrite(filepath)) + { + var data = Convert.FromBase64String(base64Content); + await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); + } + + promise.Resolve(null); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void appendFile(string filepath, string base64Content, IPromise promise) + { + try + { + // TODO: open file on background thread? + using (var file = File.Open(filepath, FileMode.Append)) + { + var data = Convert.FromBase64String(base64Content); + await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); + } + + promise.Resolve(null); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void write(string filepath, string base64Content, int position, IPromise promise) + { + try + { + // TODO: open file on background thread? + using (var file = File.OpenWrite(filepath)) + { + if (position >= 0) + { + file.Position = position; + } + + var data = Convert.FromBase64String(base64Content); + await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); + } + + promise.Resolve(null); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public void exists(string filepath, IPromise promise) + { + try + { + promise.Resolve(File.Exists(filepath) || Directory.Exists(filepath)); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void readFile(string filepath, IPromise promise) + { + try + { + if (!File.Exists(filepath)) + { + RejectFileNotFound(promise, filepath); + return; + } + + // TODO: open file on background thread? + string base64Content; + using (var file = File.OpenRead(filepath)) + { + var length = (int)file.Length; + var buffer = new byte[length]; + await file.ReadAsync(buffer, 0, length).ConfigureAwait(false); + base64Content = Convert.ToBase64String(buffer); + } + + promise.Resolve(base64Content); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void read(string filepath, int length, int position, IPromise promise) + { + try + { + if (!File.Exists(filepath)) + { + RejectFileNotFound(promise, filepath); + return; + } + + // TODO: open file on background thread? + string base64Content; + using (var file = File.OpenRead(filepath)) + { + file.Position = position; + var buffer = new byte[length]; + await file.ReadAsync(buffer, 0, length).ConfigureAwait(false); + base64Content = Convert.ToBase64String(buffer); + } + + promise.Resolve(base64Content); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void hash(string filepath, string algorithm, IPromise promise) + { + var hashAlgorithmFactory = default(Func); + if (!s_hashAlgorithms.TryGetValue(algorithm, out hashAlgorithmFactory)) + { + promise.Reject(null, "Invalid hash algorithm."); + return; + } + + try + { + if (!File.Exists(filepath)) + { + RejectFileNotFound(promise, filepath); + return; + } + + await Task.Run(() => + { + var hexBuilder = new StringBuilder(); + using (var hashAlgorithm = hashAlgorithmFactory()) + { + hashAlgorithm.Initialize(); + var hash = default(byte[]); + using (var file = File.OpenRead(filepath)) + { + hash = hashAlgorithm.ComputeHash(file); + } + + foreach (var b in hash) + { + hexBuilder.Append(string.Format("{0:x2}", b)); + } + } + + promise.Resolve(hexBuilder.ToString()); + }).ConfigureAwait(false); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public void moveFile(string filepath, string destPath, IPromise promise) + { + try + { + // TODO: move file on background thread? + File.Move(filepath, destPath); + promise.Resolve(true); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void copyFile(string filepath, string destPath, IPromise promise) + { + try + { + await Task.Run(() => File.Copy(filepath, destPath)).ConfigureAwait(false); + promise.Resolve(null); + + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void readDir(string directory, IPromise promise) + { + try + { + await Task.Run(() => + { + var info = new DirectoryInfo(directory); + if (!info.Exists) + { + promise.Reject(null, "Folder does not exist"); + return; + } + + var fileMaps = new JArray(); + foreach (var item in info.EnumerateFileSystemInfos()) + { + var fileMap = new JObject + { + { "mtime", ConvertToUnixTimestamp(item.LastWriteTime) }, + { "name", item.Name }, + { "path", item.FullName }, + }; + + var fileItem = item as FileInfo; + if (fileItem != null) + { + fileMap.Add("type", FileType); + fileMap.Add("size", fileItem.Length); + } + else + { + fileMap.Add("type", DirectoryType); + fileMap.Add("size", 0); + } + + fileMaps.Add(fileMap); + } + + promise.Resolve(fileMaps); + }); + } + catch (Exception ex) + { + Reject(promise, directory, ex); + } + } + + [ReactMethod] + public void stat(string filepath, IPromise promise) + { + try + { + FileSystemInfo fileSystemInfo = new FileInfo(filepath); + if (!fileSystemInfo.Exists) + { + fileSystemInfo = new DirectoryInfo(filepath); + if (!fileSystemInfo.Exists) + { + promise.Reject(null, "File does not exist."); + return; + } + } + + var fileInfo = fileSystemInfo as FileInfo; + var statMap = new JObject + { + { "ctime", ConvertToUnixTimestamp(fileSystemInfo.CreationTime) }, + { "mtime", ConvertToUnixTimestamp(fileSystemInfo.LastWriteTime) }, + { "size", fileInfo?.Length ?? 0 }, + { "type", fileInfo != null ? FileType: DirectoryType }, + }; + + promise.Resolve(statMap); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void unlink(string filepath, IPromise promise) + { + try + { + var directoryInfo = new DirectoryInfo(filepath); + var fileInfo = default(FileInfo); + if (directoryInfo.Exists) + { + await Task.Run(() => Directory.Delete(filepath, true)).ConfigureAwait(false); + } + else if ((fileInfo = new FileInfo(filepath)).Exists) + { + await Task.Run(() => File.Delete(filepath)).ConfigureAwait(false); + } + else + { + promise.Reject(null, "File does not exist."); + return; + } + + promise.Resolve(null); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void mkdir(string filepath, JObject options, IPromise promise) + { + try + { + await Task.Run(() => Directory.CreateDirectory(filepath)).ConfigureAwait(false); + promise.Resolve(null); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public async void downloadFile(JObject options, IPromise promise) + { + var filepath = options.Value("toFile"); + + try + { + var url = new Uri(options.Value("fromUrl")); + var jobId = options.Value("jobId"); + var headers = (JObject)options["headers"]; + var progressDivider = options.Value("progressDivider"); + + var request = new HttpRequestMessage(HttpMethod.Get, url); + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value.Value()); + } + + await _tasks.AddAndInvokeAsync(jobId, token => + ProcessRequestAsync(promise, request, filepath, jobId, progressDivider, token)); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + [ReactMethod] + public void stopDownload(int jobId) + { + _tasks.Cancel(jobId); + } + + [ReactMethod] + public async void getFSInfo(IPromise promise) + { + try + { + var properties = await ApplicationData.Current.LocalFolder.Properties.RetrievePropertiesAsync( + new[] + { + "System.FreeSpace", + "System.Capacity", + }) + .AsTask() + .ConfigureAwait(false); + + promise.Resolve(new JObject + { + { "freeSpace", (ulong)properties["System.FreeSpace"] }, + { "totalSpace", (ulong)properties["System.Capacity"] }, + }); + } + catch (Exception ex) + { + promise.Reject(null, "getFSInfo is not available"); + } + } + + [ReactMethod] + public async void touch(string filepath, double mtime, double ctime, IPromise promise) + { + try + { + await Task.Run(() => + { + var fileInfo = new FileInfo(filepath); + if (!fileInfo.Exists) + { + using (File.Create(filepath)) { } + } + + fileInfo.CreationTimeUtc = ConvertFromUnixTimestamp(ctime); + fileInfo.LastWriteTimeUtc = ConvertFromUnixTimestamp(mtime); + + promise.Resolve(fileInfo.FullName); + }); + } + catch (Exception ex) + { + Reject(promise, filepath, ex); + } + } + + public override void OnReactInstanceDispose() + { + _tasks.CancelAllTasks(); + _httpClient.Dispose(); + } + + private async Task ProcessRequestAsync(IPromise promise, HttpRequestMessage request, string filepath, int jobId, int progressIncrement, CancellationToken token) + { + try + { + using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token)) + { + var headersMap = new JObject(); + foreach (var header in response.Headers) + { + headersMap.Add(header.Key, string.Join(",", header.Value)); + } + + var contentLength = response.Content.Headers.ContentLength; + SendEvent($"DownloadBegin-{jobId}", new JObject + { + { "jobId", jobId }, + { "statusCode", (int)response.StatusCode }, + { "contentLength", contentLength }, + { "headers", headersMap }, + }); + + // TODO: open file on background thread? + var totalRead = 0; + using (var fileStream = File.OpenWrite(filepath)) + using (var stream = await response.Content.ReadAsStreamAsync()) + { + var contentLengthForProgress = contentLength ?? -1; + var nextProgressIncrement = progressIncrement; + var buffer = new byte[8 * 1024]; + var read = 0; + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) + { + token.ThrowIfCancellationRequested(); + + await fileStream.WriteAsync(buffer, 0, read); + if (contentLengthForProgress >= 0) + { + totalRead += read; + if (totalRead * 100 / contentLengthForProgress >= nextProgressIncrement || + totalRead == contentLengthForProgress) + { + SendEvent("DownloadProgress-" + jobId, new JObject + { + { "jobId", jobId }, + { "contentLength", contentLength }, + { "bytesWritten", totalRead }, + }); + + nextProgressIncrement += progressIncrement; + } + } + } + } + + promise.Resolve(new JObject + { + { "jobId", jobId }, + { "statusCode", (int)response.StatusCode }, + { "bytesWritten", totalRead }, + }); + } + } + finally + { + request.Dispose(); + } + } + + private void Reject(IPromise promise, String filepath, Exception ex) + { + if (ex is FileNotFoundException) { + RejectFileNotFound(promise, filepath); + return; + } + + promise.Reject(null, ex.Message, ex); + } + + private void RejectFileNotFound(IPromise promise, String filepath) + { + promise.Reject("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); + } + + private void SendEvent(string eventName, JObject eventData) + { + Emitter.emit(eventName, eventData); + } + + private static string GetFolderPathSafe(Func getFolder) + { + try + { + return getFolder().Path; + } + catch (UnauthorizedAccessException) + { + return null; + } + } + + public static double ConvertToUnixTimestamp(DateTime date) + { + var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var diff = date.ToUniversalTime() - origin; + return Math.Floor(diff.TotalSeconds); + } + + public static DateTime ConvertFromUnixTimestamp(double timestamp) + { + var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var diff = TimeSpan.FromSeconds(timestamp); + var dateTimeUtc = origin + diff; + return dateTimeUtc.ToLocalTime(); + } + } +} diff --git a/windows/RNFS/RNFSPackage.cs b/windows/RNFS/RNFSPackage.cs new file mode 100644 index 00000000..ecd67ccb --- /dev/null +++ b/windows/RNFS/RNFSPackage.cs @@ -0,0 +1,53 @@ +using ReactNative.Bridge; +using ReactNative.Modules.Core; +using ReactNative.UIManager; +using System; +using System.Collections.Generic; + +namespace RNFS +{ + /// + /// Package defining core framework modules (e.g., ). + /// It should be used for modules that require special integration with + /// other framework parts (e.g., with the list of packages to load view + /// managers from). + /// + public class RNFSPackage : IReactPackage + { + /// + /// Creates the list of native modules to register with the react + /// instance. + /// + /// The react application context. + /// The list of native modules. + public IReadOnlyList CreateNativeModules(ReactContext reactContext) + { + return new List + { + new RNFSManager(reactContext), + }; + } + + /// + /// Creates the list of JavaScript modules to register with the + /// react instance. + /// + /// The list of JavaScript modules. + public IReadOnlyList CreateJavaScriptModulesConfig() + { + return new List(0); + } + + /// + /// Creates the list of view managers that should be registered with + /// the . + /// + /// The react application context. + /// The list of view managers. + public IReadOnlyList CreateViewManagers( + ReactContext reactContext) + { + return new List(0); + } + } +} diff --git a/windows/RNFS/project.json b/windows/RNFS/project.json new file mode 100644 index 00000000..89d0fa70 --- /dev/null +++ b/windows/RNFS/project.json @@ -0,0 +1,16 @@ +{ + "dependencies": { + "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2" + }, + "frameworks": { + "uap10.0": {} + }, + "runtimes": { + "win10-arm": {}, + "win10-arm-aot": {}, + "win10-x86": {}, + "win10-x86-aot": {}, + "win10-x64": {}, + "win10-x64-aot": {} + } +}